在PHP中获取包含在字符串中的结果?

Kir*_*met 22 php include

假设文件test.php看起来像这样:

<?php
echo 'Hello world.';
?>
Run Code Online (Sandbox Code Playgroud)

我想做这样的事情:

$test = include('test.php');

echo $test;

// Hello world.
Run Code Online (Sandbox Code Playgroud)

有人能指出我正确的道路吗?

编辑:

我最初的目标是将PHP代码与HTML混合在一起并将其处理出来.这是我最终做的事情:

// Go through all of the code, execute it, and incorporate the results into the content
while(preg_match('/<\?php(.*?)\?>/ims', $content->content, $phpCodeMatches) != 0) {
    // Start an output buffer and capture the results of the PHP code
    ob_start();
    eval($phpCodeMatches[1]);
    $output = ob_get_clean();

    // Incorporate the results into the content
    $content->content = str_replace($phpCodeMatches[0], $output, $content->content);
}
Run Code Online (Sandbox Code Playgroud)

Sla*_*rix 57

使用输出缓冲是最好的选择.


ob_start();
include 'test.php';
$output = ob_get_clean();

Run Code Online (Sandbox Code Playgroud)

PS:请记住,如果需要,您也可以将输出缓冲区嵌套到心中.

  • 保存一行:`$ output = ob_get_clean();`;-) (6认同)

Gal*_*len 8

test.php的

<?php

return 'Hello World';

?>
Run Code Online (Sandbox Code Playgroud)
<?php

$t = include('test.php');

echo $t;

?>
Run Code Online (Sandbox Code Playgroud)

只要包含的文件有一个return语句就可以了.