如何从 PHP 中的本地脚本获取输出?

Eth*_*han 5 php

例如,在 foo.php 中:

<?php echo 'hello'; ?>
Run Code Online (Sandbox Code Playgroud)

在 bar.php 中,我想获取 foo.php 的输出(这是 hello),并在输出到浏览器之前进行一些格式化。有什么办法可以做到这一点吗?

或者更进一步,如果网络服务器可以运行 PHP 和 Python 脚本,那么 PHP 脚本是否可以获得 Python 脚本的输出?

编辑:PHP 函数 file_get_contents() 只能对远程脚本执行此操作。如果用在本地脚本上,它将返回整个脚本的内容。在上面的示例中,它返回而不是 hello。我不想使用 exec()/system() 和 CGI​​。

Sam*_*152 5

您可以使用 PHP 的输出缓冲区和函数,例如ob_start(); ob_get_contents(); 将 PHP 输出的内容读入字符串。

这是 php.net 上的示例:

<?php

function callback($buffer)
{
  // replace all the apples with oranges
  return (str_replace("apples", "oranges", $buffer));
}

ob_start("callback");

?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php

ob_end_flush();

?>
Run Code Online (Sandbox Code Playgroud)

还有另一个:

<?php
ob_start();
echo "Hello ";
$out1 = ob_get_contents();
echo "World";
$out2 = ob_get_contents();
ob_end_clean();
var_dump($out1, $out2);
?>
Run Code Online (Sandbox Code Playgroud)