Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a loop that takes very long to execute, and I want the script to display something whenever the loop iteration is done.

echo "Hello!";

flush();

for($i = 0; $i < 10; $i ++) {
    echo $i;
    //5-10 sec execution time
    flush();
}

This does not display the echos until the entire script is completed. What went wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
517 views
Welcome To Ask or Share your Answers For Others

1 Answer

From PHP Manual:

flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.

echo "Hello!";
flush();
ob_flush();

for($i = 0; $i < 10; $i ++) {
    echo $i;
    //5-10 sec execution time
    flush();
    ob_flush();
}

-or- you can flush and turn off Buffering

<?php
//Flush (send) the output buffer and turn off output buffering
while (ob_get_level() > 0)
    ob_end_flush();

echo "Hello!";

for($i = 0; $i < 10; $i ++) {
    echo $i . "
";
}

?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...