ob_start()并ob_get_clean()会为你做到这一点:
ob_start();
include "file.php";
$result = ob_get_clean();
Run Code Online (Sandbox Code Playgroud)
在ob_start()之后捕获所有回显的内容,并使用ob_get_clean()来检索捕获的数据.
你甚至可以做这样的include2功能:
function include2($file) {
ob_start();
include $file;
return ob_get_clean();
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
include2("file.php"); // return all printed values instead of really printing them
Run Code Online (Sandbox Code Playgroud)
正如@ircmaxell所指出的,此include2函数的行为include与包含更改范围(从全局到函数范围)的行为完全不同.因此,如果您依赖全局范围,这可能会破坏事物.