PHP Flush that works… even in Nginx

2019-01-10 08:57发布

Is it possible to echo each time the loop is executed? For example:

foreach(range(1,9) as $n){
    echo $n."\n";
    sleep(1);
}

Instead of printing everything when the loop is finished, I'd like to see it printing each result per time.

标签: php nginx flush
8条回答
forever°为你锁心
2楼-- · 2019-01-10 09:49

I didn't want to have to turn off gzip for the whole server or a whole directory, just for a few scripts, in a few specific cases.

All you need is this before anything is echo'ed:

header('Content-Encoding: none;');

Then do the flush as normal:

ob_end_flush();
flush();

Nginx seems to pick up on the encoding having been turned off and doesn't gzip.

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-10 09:50

You can accomplish this by flushing the output buffer in the middle of the loop.

Example:

ob_start();
foreach(range(1,9) as $n){
    echo $n."\n";
    ob_flush();
    flush();
    sleep(1);
}

Note that your php.ini settings can affect whether this will work or not if you have zlib compression turned on

查看更多
登录 后发表回答