Reputation: 33
I've found similar questions to this but none as direct. Say I have an HTML file containing an undefined PHP variable like so:
Template.html:
<!doctype html>
<html lang="${my_lang}">
</html>
And a PHP file that defines that variable and reads in the HTML file like:
Index.php:
<?php
$my_lang = "en";
$page = get_file_contents('Template.html');
?>
If I echo the $page variable the output will still be:
Processed Template.html:
<!doctype html>
<html lang="${my_lang}">
</html>
Rather than:
Expected Template.html:
<!doctype html>
<html lang="en">
</html>
I've tried using escape character quotes like:
Alternative Template.html:
<!doctype html>
<html lang=\"${my_lang}\">
</html>
To no avail. Am I looking over something obvious? Is this an example of the "variable variable" problem?
Upvotes: 3
Views: 95
Reputation: 35337
file_get_contents just reads the contents of the file into a string. Strings aren't automatically evaluated when echoing them out, that would be very troublesome.
Instead, tell the PHP interpreter to evaluate the template by using 'require' or 'include' and use valid PHP syntax in the template:
<!doctype html>
<html lang="<?= $my_lang ?>">
</html>
I'd highly recommend using phtml or php extensions on any file that has php code in it. You could also look at templating engines like Twig.
Upvotes: 3