Joe*_*oni 9 php eval output-buffering
在PHP中,我想将文件读入变量并同时处理文件中的PHP而不使用输出缓冲.这可能吗?
基本上我希望能够在不使用的情况下完成此任务ob_start():
<?php
ob_start();
include 'myfile.php';
$xhtml = ob_get_clean();
?>
Run Code Online (Sandbox Code Playgroud)
这可能在PHP?
更新:我想在输出回调中做一些更复杂的事情(不允许输出缓冲).
Wes*_*son 26
PHP的一个鲜为人知的特性是能够处理包含/需要的文件,如函数调用,具有返回值.
例如:
// myinclude.php
$value = 'foo';
$otherValue = 'bar';
return $value . $otherValue;
// index.php
$output = include './myinclude.php';
echo $output;
// Will echo foobar
Run Code Online (Sandbox Code Playgroud)
在阅读了每个人的建议、阅读了一堆文档并尝试了一些东西之后,我想出了这个:
<?php
$file = file_get_contents('/path/to/file.php');
$xhtml = eval("?>$file");
?>
Run Code Online (Sandbox Code Playgroud)
这是我能得到的最接近的结果,但不幸的是它不起作用。关键是?>在文件内容之前包含 PHP 结束位 ( )。这将退出eval()PHP 评估模式,并将文件的内容视为非 PHP 代码。然后,如果文件中有 PHP 代码块,这些代码块将被评估为 PHP。令人遗憾的是,它不会将评估的内容保存在变量中,而只是将其输出到页面。
谢谢大家的帮助!