问题
For part of my website I need to be able to write php code to a file with php. For example:
$filename = "RtestR.php";
$ourFileName =$filename;
$ourFileHandle = fopen($ourFileName, 'w');
$written = "
<html>
<body>
<?php
echo \"I like the color \".$_SESSION['color'].\"!!!!\";
</body>
</html>
";
fwrite($ourFileHandle,$written);
fclose($ourFileHandle);
But, instead of creating the file, it throws this error:
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING on line 14
What am I doing wrong and what is the right way to write php code to a file?
EDIT:
I think I might need to make myself clearer... I want the SESSION to be determined when the newly created file is loaded. Technically I don't want to get the session on this page, but instead on the page I am creating!!! I want to write the code to the file, not the output of the code!
回答1:
Finally figured this out!
I needed to escape my $
symbols!
Like this:
$written = "
<html>
<body>
<?php
echo \"I like the color \".\$_SESSION['color'].\"!!!!\";
</body>
</html>
";
Can't believe i didn't think of that ;)
Thank you all!
回答2:
You can do like this :-
<?php
$filename = "RtestR.php";
$ourFileName =$filename;
$ourFileHandle = fopen($ourFileName, 'w');
$written = "<html>
<body>
I like the color ".$_SESSION['color']."!!!!
</body>
</html> ";
fwrite($ourFileHandle,$written);
fclose($ourFileHandle);
?>
回答3:
It seems relevant to mention php's HEREDOC in this context, e.g.:
<?php
$filename = 'RtestR.php';
$ourFileName = $filename;
$ourFileHandle = fopen($ourFileName, 'w');
$write = <<<"FILE_CONTENTS"
<p>I like the color <?={$cleanSessionVars[ 'color' ]};?>.</p>
FILE_CONTENTS;
fwrite($ourFileHandle, $write);
fclose($ourFileHandle);
回答4:
You're missing your closing PHP tag ?>
.
Consider for a moment that what you are doing might not be the best approach anyway. The only use case I can think of for writing out PHP files with PHP would be for some compiled template code or weird caching.
回答5:
Hello pattyd: Nice to see ya :) + Don't upvote/accept this answer:
I would suggest simplified in this way:
$written = "
<html>
<body>
I like the color \" $_SESSION['color'] \" !!!!
</body>
</html>
";
回答6:
$fp = fopen("test.php", "w");
$string = '<html>
<body>
<?php
echo "I like the color ".$_SESSION[\'color\']."!!!!";
?>
</body>
</html>';
fwrite($fp, $string);
fclose($fp);
来源:https://stackoverflow.com/questions/17029917/how-to-write-php-code-to-a-file-with-php