这与输出缓冲有关.如果打开输出缓冲,则输出不会立即发送到客户端,而是等待缓冲一定量的数据.这通常会提高性能但会导致像您这样的问题.
简单的解决方案不需要更改任何php.ini设置,只需将其放在脚本的开头:
while (@ob_end_flush());
?>
这将立即刷新并禁用所有输出缓冲.
您可能还想阅读Output Control上的PHP手册.相关的php.ini设置列于here.
如果您想确保发送内容(即在耗时的任务之前),请在适当的时间拨打flush().
编辑:
事实上,浏览器可能有自己的缓冲区,特别是当没有显式设置Content-Type时(浏览器需要嗅探文件的MIME类型).如果是这种情况,则无法控制浏览器的行为.
可能解决它的一种方法是显式设置Content-Type:
header("Content-Type: text/plain"); // if you don't need HTML
// OR
header("Content-Type: text/html");
但这并不能保证有效.它适用于我的Firefox但不适用于Chrome.
无论如何,您的最终代码应如下所示:
header("Content-Type: text/html"); // Set Content-Type
while (@ob_end_flush()); // Flush and disable output buffers
while ($a++ < 5) {
$b = 0;
while ($b++ < 1015) {
echo "H";
//flush(); // In fact because there is no significant delay, you should not flush here.
}
echo "
\n";
flush(); // Flush output
sleep(1);
}