Php – Include dynamic PHP in generated php file


I'm trying to generate php files that 'include' a template html file, as so:

$page = htmlspecialchars("Hello! <?php include("template.html"); ?>");

But, when I run it, I get:

Parse error: syntax error, unexpected T_STRING in /home/oliver/web/ on line 15

I'm pretty sure I need to escape the PHP code, just not sure how.

Best Solution

You have to escape any double quotes inside strings that are declared in double quotes. So this should work:

$code = "Hello! <?php include(\"template.html\"); ?>";

See PHP manual about strings.

And if you want to put that code into a file, you could use the file_put_contents function:

file_put_contents('myscript.php', $code);