Display the output while looping in php

2020-03-24 08:43发布

Is it possible to display string on the browser while in infinite loop? This is what I want to happen:

while(1) {
     echo "should display these lines on browser while in infinite loop.<br>";
}

标签: php
4条回答
聊天终结者
2楼-- · 2020-03-24 08:56

Add flush() after the echo statement, it will flush the output to the browser. Note that browsers generally don't start to render until their reach a certain amount of information (around .5kB).

while(1) {
     echo "should display these lines on browser while in infinite loop.<br>";
     flush(); //Flush the output buffer
}
查看更多
淡お忘
3楼-- · 2020-03-24 08:59

If you don't want to put flush(); after each echo of your code:

Set this in your php.ini:

implicit_flush = Off

Or if you don't have access to php.ini:

@ini_set('implicit_flush',1);

查看更多
叛逆
4楼-- · 2020-03-24 09:02

Yes, it is possible. You need to flush the output to the browser if you want it to appear immediately:

while(1) {
     echo "should display these lines on browser while in infinite loop.<br>";
     flush();
}

Chances are that whatever you're trying to accomplish, this isn't how you should go about it.

PHP will eventually time-out, but not before it generates a massive HTML document that your browser will have trouble displaying.

查看更多
家丑人穷心不美
5楼-- · 2020-03-24 09:07

Notice the use of ob_flush(); to make sure php outputs, and usleep(100000) to have time to see things happening.

while(1) {
     echo "should display these lines on browser while in infinite loop.<br>";
     usleep(100000); // debuging purpose
     ob_flush();
     flush();
}
查看更多
登录 后发表回答