Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

php - Echo 'string' while every long loop iteration (flush() not working)

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

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

1 Reply

0 votes
by (71.8m points)

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 . "
";
}

?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...