【问题标题】:PHP Output buffering on the command line命令行上的 PHP 输出缓冲
【发布时间】:2011-04-05 18:15:57
【问题描述】:

我有一个要在命令行上运行的 PHP 脚本。除其他外,该脚本需要加载一个包含 PHP 和 HTML 内容的 PHP 文件,并从该文件中获取渲染输出。

这段代码完全符合我的需要,但不是从命令行运行时:

<?php

// ...
if(file_exists($content_file)) {
  ob_start();
  include($content_file);
  $content = ob_get_contents();
  ob_end_clean();
}

?>

在浏览器中运行时,我的脚本通过 include() 获取 PHP 文件的渲染输出,并将输出存储在 $content 中。

但是,当我在命令行上执行此脚本时,PHP 文件的内容会被回显,并且 $content 永远不会被设置。

我已经搜索了文档,但似乎没有任何效果。调用 ini_set('implicit_flush', false) 没有效果,ob_implicit_flush(0);

有什么想法吗?

【问题讨论】:

  • 尝试通过在包含前添加 @ 来消除错误:@include($content_file);
  • @Raisen,这里没有错误,使用@错误静默操作符通常被认为是一种不好的做法。
  • 你能包含你用来调用脚本的命令吗?我知道这是一个长远的目标,但这可能会影响您的输出。
  • 来自不太可能但可能的错误部门:尝试ob_start(NULL,0),并确保您的包含文件中不存在ob_flush()

标签: php command-line output-buffering


【解决方案1】:

我无法使用 PHP 5.3 重现此问题。

[charles@lobotomy ~]$ cat includeme.php
<?php

echo "Oh hi!\n";
?>
I am an include!

[charles@lobotomy ~]$ cat includehim.php
<?php

$content_file = './includeme.php';

if(file_exists($content_file)) {
  ob_start();
  include($content_file);
  $content = ob_get_contents();
  ob_end_clean();
}
[charles@lobotomy ~]$ php includehim.php
[charles@lobotomy ~]$

在交互式提示下:

[charles@lobotomy ~]$ php -a
Interactive shell

php > $content_file = './includeme.php';
php > if(file_exists($content_file)) {
php {   ob_start();
php {   include($content_file);
php {   $content = ob_get_contents();
php {   ob_end_clean();
php { }
php >
php > echo $content;
Oh hi!
I am an include!

php > exit;

【讨论】:

  • 我在使用 PHP5.3 时遇到了完全相同的问题 - CakePHP2.0 和 Shells 似乎忽略了 ob_start() 等。可能是因为 shell 在 CLI 级别左右运行?就我而言,我想捕捉“system('dos2unix -h', $x);”的结果但它总是把它打印出来......
  • @mark,您可能想使用execproc_open 而不是systemsystem 故意拧紧输出缓冲区。
  • 谢谢。我也使用 exec 没有成功。奇怪的是: exec('svn/git') 有效。输出未刷新但正确返回。 proc_open 我从未听说过。会试一试的!
猜你喜欢
  • 2011-07-24
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 2016-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多