Is there a need for web development that needs to be timed to output the results to a browser page without refreshing the entire page? What do you do when you're dealing with a process that takes a long time, but you need to know the current state of the process in a timely manner? Here's how to use PHP in time to output the current results to the browser without refreshing the entire page effect.
Here is a simple example to illustrate the problem. First look at a piece of code:
<?php for
($i =0; $i <10; $i + +) {
echo $i;
Sleep (1);
}
? >
The above program, if executed in the PHP interpreter, outputs a number per second, as expected. But when accessed in the browser, the result is that the browser displays all the results once in 10 seconds. For this issue, we can use Ob_flush () and flush () to force the refresh of the browser cache, and the program should read:
<?php
//author www.Alixixi.com for
($i =0; $i <10; $i + +) {
echo $i;
Ob_flush ();
Flush ();
Sleep (1);
}
? >
Problem solved, but another problem, the browser is not compatible. In the actual test, only Firefox output the results on the basis of the expected effect, and in the browser such as IE Safari Opera is a one-time output results. Check the relevant data found because different browsers to buffer processing different ways, Firefox is required to force flush cache is very obedient, and IE needs to receive 256 bytes before the content of real-time display in the interface, Safari needs 1024 bytes, Opera more personality, The instant output occurs only when an HTML tag is encountered (as is the case with Safari).
For the above questions, for IE and Safari, you can output a blank character larger than the qualified number before the output:
<?php
Echo str_repeat ("", 1024);
For ($i =0 $i <10; $i + +) {
echo $i;
Ob_flush ();
Flush ();
Sleep (1);
}
? >
And for opera, Safari encountered HTML tags will be immediately output problems, because generally we will not only to the browser output plain text content, it can not be considered. For the above program, you can add HTML tags to the output to achieve the goal:
<?php
Echo str_repeat ("", 1024);
For ($i =0 $i <10; $i + +) {
echo $i. " <br> ";
Ob_flush ();
Flush ();
Sleep (1);
}
? >
At this point has been basically achieved in the various browsers to achieve consistent results, as for the actual work, you may be another purpose but need to be similar to this effect, you only need to make the appropriate changes.