我正在编写一个命令行 PHP 脚本,它会在控制台窗口输出一些内容,一切看起来都很好,唯一的问题是当我输入
php myfilename.php -....
在控制台窗口中,仅在完全执行后才将结果输出到窗口。
我想要的是像下面这样实时进行:
customer id: 1223 skipped.
customer id: 22233 added..
另一个问题是在printf函数中添加\n\r不能换行...
对这些问题有什么想法吗?
我正在编写一个命令行 PHP 脚本,它会在控制台窗口输出一些内容,一切看起来都很好,唯一的问题是当我输入
php myfilename.php -....
customer id: 1223 skipped.
customer id: 22233 added..
另一个问题是在printf函数中添加\n\r不能换行...
对这些问题有什么想法吗?
这可能是由于输出缓冲导致的。您可以在需要时使用ob_flush()
手动刷新缓冲区。
至于您的第二个问题,在Microsoft Windows上换行符的正确顺序是"\r\n"
,而不是相反的顺序。
首先,Windows风格的换行符是\r\n
,而不是\n\r
。很少有系统使用\n\r
,但它们已经足够罕见,现在可以忘记它们了。
其次,输出很可能是被块缓冲的--你可以使用ob_implicit_flush(1)
来在每个输出命令后自动插入flush()
命令。或者,在需要刷新输出时手动调用flush()
。
PHP_EOL
; 它将根据您的平台正确设置,因此您不必担心它是否正确。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。它们是非常强大的工具。
希望这能帮到你。干杯!