如何将包含内容作为字符串?

ppp*_*ppp 9 php include

可能重复:
执行PHP文件,并将结果作为字符串返回
PHP捕获print/require输出变量

我试图将包含的内容添加到字符串中.那可能吗?

例如,如果我有一个test.php文件:

echo 'a is equal to '.$a;
Run Code Online (Sandbox Code Playgroud)

我需要一个函数,比如说include_to_string包含test.php并返回字符串输入的内容.

就像是:

$a = 4;
$string = include_to_string(test.php); // $string = "a is equal to 4"
Run Code Online (Sandbox Code Playgroud)

Dav*_*dom 32

ob_start();
include 'test.php';
$string = ob_get_clean();
Run Code Online (Sandbox Code Playgroud)

我想是你想要的.请参阅输出缓冲.

  • 对于任何好奇的人来说,这种技术称为输出缓冲. (2认同)

fir*_*ire 5

ob_start();
include($file);
$contents = ob_get_contents(); // data is now in here
ob_end_clean();
Run Code Online (Sandbox Code Playgroud)