Can I load a file in PHP as a string with inline variables?
I've got a simple (but not tiny) template for some HTML, complete with inline variables. I'd like to pull that out as a separate file, and have the ability to switch in other template files. Is there a way to load a file into a string, but have it process inline variables?
Eg:
$thing="complete sen开发者_Go百科tence";
$test=<<<END
This will get parsed as a $thing.
END;
echo $test; // This will get parsed as a complete sentence.
What I want is something like this:
// "test.html"
<html>
<body>
<p>This will get parsed as a $thing.</p>
</body>
// "index.php"
$thing="complete sentence";
$test=file_get_contents("test.html");
echo $test; // This will get parsed as a complete sentence.
How do I achieve this, preferably without a templating library?
<?php
$thing="complete sentence";
$test=file_get_contents("test.php");
echo preg_replace_callback('#\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)#','changeVariables',$test);
function changeVariables($matches)
{
return $GLOBALS[$matches[1]];
}
This code uses preg_replace_callback
to check what is variable. But, because we are in function
, we cannot directly access script variables. We have to use $_GLOBALS
variable which contains every script variable. $matches[1]
contains name of matched variable.
Something like this should work...
// "test.php"
This will get parsed as a %s.
// "index.php"
$thing="complete sentence";
$test=file_get_contents("test.php");
printf($test, $thing);
You can use include
to simply load the file as if it were part of the calling code.
include("included_file.php");
If you cannot include
for some reason, you can read the file contents and eval
it.
$content = file_get_contents("included_file.php");
eval($content);
UPDATE:
As pointed by NikiC, your file test.html doesn't have valid PHP. You would have to change it so include
can work. Your test.html should have this content:
<html>
<body>
<p>This will get parsed as a <?= $thing ?>.</p>
</body>
And eval
would not work with this code, as this is not pure PHP code, it is HTML code with PHP inside it. If your included file has just PHP code, it would work fine.
精彩评论