PHP - 操作后从文件中打印内容

时间:2010-04-22 20:15:06

标签: php string file compilation printf

我正在努力尝试在php中读取一个php文件并进行一些操作..之后将内容作为字符串,但当我尝试使用echo或print输出时,所有的php标签都包含在字面上文件。

所以这是我的代码:

function compilePage($page,$path){
   $contents = array();
   $menu = getMenuFor($page);
   $file = file_get_contents($path);
   array_push($contents,$menu);
   array_push($contents,$file);
   return implode("\n",$contents);
}

这会返回一个像

这样的字符串
<div id="content>
   <h2>Here is my title</h2>
   <p><? echo "my body text"; ?></p>
</div>

但是这将完全打印上面的内容而不是编译php。

那么,我怎样才能渲染这个“compilePage”,确保它返回一个已编译的php结果,而不只是一个纯文本?

提前致谢

3 个答案:

答案 0 :(得分:1)

您可以使用output buffering来正常使用include文件:

function compilePage($page,$path){
   $contents = array();
   $menu = getMenuFor($page);
   ob_start();
   include $path;
   $file = ob_get_contents();
   ob_end_clean();
   array_push($contents,$menu);
   array_push($contents,$file);
   return implode("\n",$contents);
}

include()调用将正常包含PHP文件,并且将解析并执行<?php块。任何输出都将由使用ob_start()创建的缓冲区捕获,您可以稍后使用其他ob_*函数获取它。

答案 1 :(得分:1)

function compilePage($page, $path) {
    $contents = getMenuFor($page);
    ob_start();
    include $path;
    $contents .= "\n".ob_get_clean();
    return $contents;
}

要评估字符串中的PHP代码,请使用eval函数,但高度未经修改。如果您有包含PHP代码的文件,则可以根据需要使用includeinclude_oncerequirerequire_once对其进行评估。要捕获所包含文件的输出 - 或必需,或以任何方法 - 您需要启用output buffering

答案 2 :(得分:0)

您需要使用include()才能执行。您可以将此与output buffering结合使用以获得字符串中的返回值。

function compilePage($ page,$ path){     $ contents = array();     $ menu = getMenuFor($ page);

//output buffer
ob_start();
include($path);
$file = ob_get_contents();
ob_end_clean();   

array_push($contents,$menu);
array_push($contents,$file);
return implode("\n",$contents);

}