简体   繁体   English

为什么 ob_flush 和 flush 对浏览器的即时 output 不起作用?

[英]Why doesn't ob_flush and flush work for immediate output to browser?

I try to output data from PHP to the browser immediately everytime there is some data to send.每次有一些数据要发送时,我都会立即尝试将 output 数据从 PHP 发送到浏览器。 I've searched for a solution and ended up with the code below where each line should be shown in the browser every second.我已经搜索了一个解决方案并以下面的代码结束,其中每行应该每秒显示在浏览器中。

This should work according to the PHP manual and other sites.这应该根据 PHP 手册和其他站点工作。 But for me it doesn't.但对我来说不是。 The browser waits for 5 seconds and displays everything at once.浏览器等待 5 秒并立即显示所有内容。 I have tried on latest versions of Firefox, Chrome and IE and I can't figure out why the result isn't shown after each ob_flush/flush.我试过最新版本的 Firefox、Chrome 和 IE,但我无法弄清楚为什么在每次 ob_flush/flush 后没有显示结果。 Can anyone explain?谁能解释一下?

<?php
header( 'Content-type: text/html; charset=utf-8' );
ob_implicit_flush(true);
ob_start();

for ($i = 0; $i<5; $i++){
    echo "<p>{$i}. Displaying one line...</p>";
    echo str_pad('',4096)."\n";   

    ob_flush();
    flush();

    sleep(1);
}

echo "Done.";
ob_end_flush();
?>

Note: I have also experimented on using ob_end_flush at the beginning, removing the header line, sending longer echo strings, read other posts on Stack Overflow, etc.. The browser still waits until the output is done.注意:我也尝试过在开始时使用 ob_end_flush,删除 header 行,发送更长的回显字符串,阅读 Stack Overflow 上的其他帖子等。浏览器仍在等待 output 完成。

This simple code works in Chrome and Edge.这个简单的代码适用于 Chrome 和 Edge。 The numbers are displayed as the flush occurs.数字在冲洗发生时显示。 But not in Firefox. In Firefox everything is displayed when the PHP script ends.但不是在 Firefox 中。在 Firefox 中,当 PHP 脚本结束时,所有内容都会显示。

<?php
for ($i = 0; $i < 5; $i++)
{
    echo "i==$i<br>\n";
    flush();
    @ob_flush();
    sleep(1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM