Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-操作后从文件打印内容_Php_String_File_Compilation_Printf - Fatal编程技术网

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

PHP-操作后从文件打印内容,php,string,file,compilation,printf,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); arra

我正在努力读取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>
您可以使用它,并且
通常包括文件:

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文件,您需要使用()才能执行。您可以将其与以字符串形式获取返回

函数编译页($page,$path){ $contents=array(); $menu=getMenuFor($page)

}


要在字符串中计算PHP代码,可以使用函数,但这是非常不明智的。如果您有一个包含PHP代码的文件,您可以根据需要使用、或对其进行评估。要捕获包含文件的输出-或必需的,或任何方法-您需要启用。

谢谢erisco,我不确定其他解决方案,但这似乎是最简单的解决方案。:)cheersphp.net/variables.scope将告诉您在函数外部定义的变量在函数内部不可用。要访问这些变量,您需要使用
global
语句。你可能会想考虑这个模板解决方案,而不是:
//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);
function compilePage($page, $path) {
    $contents = getMenuFor($page);
    ob_start();
    include $path;
    $contents .= "\n".ob_get_clean();
    return $contents;
}