开发者

Display output in parts in PHP

开发者 https://www.devze.com 2023-01-29 11:44 出处:网络
I have this code: <?php for($i = 0; $i<30; $i++) { echo \"$i<br>\"; usleep(100000); } ?> I would like to know how make the browser display 0, then 1, t开发者_StackOverflowhen 2, ..

I have this code:

<?php
for($i = 0; $i<30; $i++)
{
    echo "$i<br>";          
    usleep(100000); 
}

?>

I would like to know how make the browser display 0, then 1, t开发者_StackOverflowhen 2, ...

In my example, it loads for a while and then display 0-29.


Disable all output buffering and pad the output:

while(@ob_get_clean());

for($i = 0; $i<30; $i++)
{
    echo str_pad("$i<br>",4096);          
    usleep(100000); 
}

Also, this won't work, if your Apache is using mod_deflate and you have gzip-compression for text/html files.


Flush the output buffer manually:

<?php
ob_start();
for($i = 0; $i<30; $i++)
{
    echo "$i<br>";
    ob_flush();
    usleep(100000); 
}
?>


Another perhaps quicker way is to do

<?php ob_implicit_flush(true); ?> 

to tell php to flush the output buffer after each output, not at the end of the file being processed.


Use javascript. HTML isn't an interactive console.

EDIT: Those of you downvoting, please remember that I am proposing an actual working solution. Incremental output from php is in no way a valid solution here, because there are some many places along the way where it could get buffered, and browsers are in no way obligated to render html incrementally as it comes in.


In my experience there is no reliable way to make a webpage send output data in realtime.

There are many different places where it can go wrong - and while you can easily get it to work on a single situation there will always be other places where the solution does not work.

Ultimately the only reliable solution is to execute your php code from a shell prompt (via SSH or whatever) and completely bypass apache and web browsers.


<?php
header('Content-type: text/html; charset=utf-8');
@ini_set('zlib.output_compression',0);
@ini_set('implicit_flush',1);
@ob_end_clean();
set_time_limit(0);

echo "Yes";
sleep(5);
echo " sir";

Don't ask me to explain it, but this works for me.

0

精彩评论

暂无评论...
验证码 换一张
取 消