如何将 PHP 包含定义为字符串?
我试过了:
$test = include 'test.php';
但这只包括正常文件
您需要查看输出缓冲函数。
//get anything that's in the output buffer, and empty the buffer
$oldContent = ob_get_clean();
//start buffering again
ob_start();
//include file, capturing output into the output buffer
include "test.php";
//get current output buffer (output from test.php)
$myContent = ob_get_clean();
//start output buffering again.
ob_start();
//put the old contents of the output buffer back
echo $oldContent;
编辑:
正如Jeremy所指出的,输出缓冲区堆叠。所以从理论上讲,你可以做这样的事情:
<?PHP
function return_output($file){
ob_start();
include $file;
return ob_get_clean();
}
$content = return_output('some/file.php');
这应该等同于我更详细的原始解决方案。
但是我没有费心去测试这个。
试试下面这些方法:
ob_start();
include('test.php');
$content = ob_get_clean();