PHP的file_get_contents与php完好无损?

joh*_*ack 8 php include

与使用include,在文件中执行包含的php相反...是否可以将php文件的内容保存到变量 - 但是php仍然完整且可执行?

我的目标看起来像:

$template = some_imaginary_include_function('myfile.php');
foreach($list_of_blogs as $blog) {
    // somehow get blog content in template and render template;
}
Run Code Online (Sandbox Code Playgroud)

我知道那是一个愚蠢的例子......但我希望它能说明一般的想法.如果我必须在页面上循环模板50次(比如它是一个博客列表),实际运行并包含每个模板似乎都很愚蠢.

我错了吗?有没有办法做到这一点?

ale*_*lex 20

这个怎么样...

function getTemplate($file) {

    ob_start(); // start output buffer

    include $file;
    $template = ob_get_contents(); // get contents of buffer
    ob_end_clean();
    return $template;

}
Run Code Online (Sandbox Code Playgroud)

基本上,这将获得任何东西$file,并用PHP解析它,然后将输出返回到变量.