Does web development need to output results to the browser page in a timely manner without refreshing the entire page? What should you do when it takes a long time to process a process, but you need to know the current processing status of the program in a timely manner? Next we will share with you how to use php to timely output the current results to the browser without refreshing the entire page. The following is a simple example to illustrate this problem. First, let's look at a piece of code: & lt ;? Phpfor ($ i0; $ I & lt; 10; $ I ++) {echo $ I; does web development need to output results to the browser page in a timely manner without refreshing the entire page?
What should you do when it takes a long time to process a process, but you need to know the current processing status of the program in a timely manner?
Next we will share with you how to use php to timely output the current results to the browser without refreshing the entire page. The following is a simple example to illustrate this problem. First, let's look at a piece of code:
for($i=0;$i<10;$i++){
echo $i;
sleep(1);
}
?>
If the above program is executed in the PHP interpreter, a number is output per second, which is the same as expected. However, when accessed in a browser, the result is that the browser displays all the results in ten seconds. For this problem, we can use ob_flush () and flush () to forcibly refresh the browser cache. The program is changed:
//author www.scutephp.com
for($i=0;$i<10;$i++){
echo $i;
ob_flush();
flush();
sleep(1);
}
?>
The problem is solved, but the browser is not compatible. In actual tests, only Firefox outputs results in real time based on the expected results, while IE Safari Opera and other browsers still output results at one time. I found that different browsers have different processing methods for caching. Firefox is obedient when it is required to forcibly refresh the cache, IE needs to receive 256 bytes before it can instantly display the content on the interface. Safari requires 1024 bytes, and Opera is more personalized, real-time output is only available when HTML tags are encountered (as is Safari ). For the above issues, for IE and Safari, you can output White spaces larger than the limit before the output:
echo str_repeat(" ",1024);
for($i=0;$i<10;$i++){
echo $i;
ob_flush();
flush();
sleep(1);
}
?>
For Opera and Safari, HTML tags are output in real time. because we generally do not only output plain text content to the browser, we can leave it empty. For the above program, you can add HTML tags to the output result to achieve the goal:
echo str_repeat(" ",1024);
for($i=0;$i<10;$i++){
echo $i."
";
ob_flush();
flush();
sleep(1);
}
?>
So far, we have basically achieved consistent results in various browsers. as for actual work, you may have another purpose, but you need to do something similar, you only need to make corresponding modifications as needed.