Php命令行实时输出

6

我正在编写一个命令行 PHP 脚本,它会在控制台窗口输出一些内容,一切看起来都很好,唯一的问题是当我输入

php myfilename.php -....

在控制台窗口中,仅在完全执行后才将结果输出到窗口。
我想要的是像下面这样实时进行:
customer id: 1223 skipped.
customer id: 22233 added..

另一个问题是在printf函数中添加\n\r不能换行...

对这些问题有什么想法吗?

3个回答

6

这可能是由于输出缓冲导致的。您可以在需要时使用ob_flush()手动刷新缓冲区。

至于您的第二个问题,在Microsoft Windows上换行符的正确顺序是"\r\n",而不是相反的顺序。


第一个问题似乎已经解决了,即使我使用"\r\n",它在控制台中并没有输出新行,但如果我在代码中输入回车键,它就可以正常工作。 - mahen3d

5

3
关于行尾标记,始终使用PHP预定义常量PHP_EOL; 它将根据您的平台正确设置,因此您不必担心它是否正确。
对于[Enter]问题,可能是输出缓冲区已开启。在您的脚本中添加这个简单的测试:
function test()
{
    $state = array(' added', ' skipped');
    for ($i = 0; $i < 50; $i++)
    {
        echo 'customer id: ' . rand(1, 1000) . $state[rand(0, 1)] . PHP_EOL;
        usleep(50000); // slow it a bit to see the line by line output
    }
}

// without ob -------------------------------------------

$start = microtime(true);
test();
echo 'Finished in ' . round(microtime(true) - $start, 2) . PHP_EOL . str_repeat('-', 78) . PHP_EOL;
sleep(1);

// with ob ----------------------------------------------

$start = microtime(true);
ob_start(); // if called somewhere at the top in your script

// some previous code...
echo 'Line 1'.PHP_EOL.'Line 2'.PHP_EOL.uniqid().PHP_EOL;

// flush the buffer and stop ob
// this will echo whatever is in the output buffer!
//ob_end_flush();

// or, store the current buffer content in a variable and use it later
$output = ob_get_clean();

test();
echo $output;
echo 'Finished in ' . round(microtime(true) - $start, 2) . PHP_EOL . str_repeat('-', 78) . PHP_EOL;

// you could start buffering again, if needed
ob_start();

有关输出控制函数,请参见http://www.php.net/manual/en/ref.outcontrol.php。它们是非常强大的工具。

希望这能帮到你。干杯!


上面的帖子解决了我苦恼了好几天的问题,即使它并不是直接相关的。我以为我有一个缓冲区问题。结果证明,我只需要在我的echo语句末尾添加PHP_EOL就可以将stdout输出到我的日志文件中。这是我浪费了数小时时间却最简单的事情。 - fred

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接