Log in

View Full Version : write php code using fwrite



nicmo
04-23-2009, 03:58 PM
hi, i am trying to update a file every so often with a couple of variables. having some troubles tho.


$strsql = "select tip_text from tips order by rand() limit 1";
$resulttip=query($strsql);

$tip_text = $resulttip[0][tip_text];

$myFile = "../../includes/siteglobal_cache.php";
$fh = fopen($myFile, 'w') or die("can't open file");

$fileData = '<? ';
$fileData .= ' $site_tip_text = $tip_text; ';

$fileData .= ' ?>';

fwrite($fh, $fileData);
fclose($fh);




what i want the siteglobal_cache.php to be saved is for example:



<? $site_tip_text = "never eat too many <a href="cookies.php">cookies</a>"; ?>


as you can see there is a problem with all the " and '... i am a bit lost, can someone clarify on how i should edit this code please? cheers

Master_script_maker
04-23-2009, 11:05 PM
"" allows variables to be in it, while '' is purely textual, no variables. If you take the variable out of quotes it should work:
$fileData .= ' $site_tip_text = ' . $tip_text . '; ';

nicmo
04-24-2009, 05:27 PM
that would come up as



<? $site_tip_text = never eat too many <a href="cookies.php">cookies</a>; ?>


wich doesnt work :)



$fileData .= ' $site_tip_text = "' . $tip_text . '"; ';


works on tips that dont have html... in the example above it would not work because of the HTML's ""

what to do? :(

Schmoopy
04-24-2009, 06:22 PM
This is sort of confusing me with all the variables and different single quotes and double quotes but this:



<? $site_tip_text = "never eat too many <a href="cookies.php">cookies</a>"; ?>


Could be changed to :



<? $site_tip_text = "never eat too many <a href=\"cookies.php\">cookies</a>"; ?>


This now escapes the double quote and instead of terminating the string outputs the literal double quote.

This may not be what you're looking for but I'm still sort of confused by what you've put. Just tell me if what I've said helps you in any way.

nicmo
04-24-2009, 08:49 PM
ok, did the following and seems to be working!



$strsql = "select tip_text from tips order by rand() limit 1";
$resulttip=query($strsql);

$tip_text = str_replace(array('"'), '\"',$resulttip[0][tip_text]);

$myFile = "../../includes/siteglobal_cache.php";
$fh = fopen($myFile, 'w') or die("can't open file");


$fileData = '<? ';
$fileData .= ' $site_tip_text = "' . $tip_text . '"; ';

$fileData .= ' ?>';

fwrite($fh, $fileData);
fclose($fh);