我可以在PHP中加载一个带有内联变量的字符串文件吗?


Can I load a file in PHP as a string with inline variables?

我有一个简单的(但不是很小的)HTML模板,完成内联变量。我想把它拉出来作为一个单独的文件,并有能力在其他模板文件切换。是否有一种方法可以将文件加载到字符串中,但要处理内联变量?

,

$thing="complete sentence";
$test=<<<END
    This will get parsed as a $thing.
END;
echo $test; // This will get parsed as a complete sentence.

我想要的是这样的:

// "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.

我如何实现这一点,最好没有模板库?

<?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]];
    }

这段代码使用preg_replace_callback检查什么是变量。但是,因为我们在function中,我们不能直接访问脚本变量。我们必须使用$_GLOBALS变量,它包含每个脚本变量。$matches[1]包含匹配变量的名称

像这样的东西应该可以工作…

// "test.php"
This will get parsed as a %s.
// "index.php"
$thing="complete sentence";
$test=file_get_contents("test.php");
printf($test, $thing);

您可以使用include来简单地加载文件,就好像它是调用代码的一部分。

include("included_file.php");

如果由于某种原因不能include,您可以读取文件内容并eval它。

$content = file_get_contents("included_file.php");
eval($content);

更新:

正如NikiC指出的,您的文件test.html没有有效的PHP。你必须改变它,使include可以工作。你的test.html应该有这样的内容:

<html>
<body>
    <p>This will get parsed as a <?= $thing ?>.</p>
</body>

eval将不与此代码工作,因为这不是纯PHP代码,它是HTML代码与PHP里面。如果包含的文件只有PHP代码,则可以正常工作。