3

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?

3
  • What are you trying to achieve? What you are seeing is corrected -- you are basically just reading a file and dumping out it's contents. What are you trying to accomplish? Commented Sep 22, 2018 at 0:12
  • 1
    You seem to be assuming that when you read the file in with get_file_contents it will search the string for a token ( ${var} ) and replace the token with a matching currently defined variable. You are going to have to do this on your own if you want it to happen. Commented Sep 22, 2018 at 0:12
  • There are templating frameworks for PHP, you should search for them and use that. Commented Sep 22, 2018 at 0:43

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Why the curly brackets? Also, my_lang should be wrapped in quotes if the brackets stay.
Yeah, I just quickly copied the OP's variable, the brackets shouldn't be used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.