Home >Backend Development >PHP Tutorial >PHP outputs data line by line and solves two common buffering problems
The blogger is keen on various Internet technologies. He is often wordy and often accompanied by obsessive-compulsive disorder. He updates frequently. If you think the article is helpful to you, you can follow me. Please indicate "Dark Blue Scythe" when reprinting
1. Encountered a problem
I wonder if you have encountered these two situations:
Okay, if you encounter the above two situations, or you may face such a problem in the future, you can mark it so that it can be solved quickly next time.
2. Principle
Back to business.
The following is a grand introduction to PHP output control Output buffer
First of all, try the effect of the following code
<?php if (ob_get_level() == 0){ ob_start() }else{ exit(0);};//开始缓冲 for ($i = 0; $i<10; $i++){ echo "Line to show.\n<br />";//不直接输出,先存入缓冲区中 ob_flush();//将缓冲区的数据输出出来 flush();//将缓冲区的数据输出出来 sleep(2);//暂停两秒 } echo "Done."; ob_end_flush();//关闭并清理缓冲区
The principle is that PHP puts the data into the Buffer before outputting the data, and then outputs the buffered data when needed. Please be careful not to confuse this with the Cache.
The advantage of this is that on the one hand, it can achieve cool effects similar to delayed loading, on the other hand, it can also reduce the pressure on the server and client, otherwise there will be insufficient memory when outputting big data.
Note: ob_flush() and flush() are both used to flush buffer data, but the official recommendation is to use them together, because although only ob_flush() is used in most WebServers You can flush out the buffer, but in some cases, such as apache, you sometimes need to call flush(), so for the portability of your code, it is recommended to see ob_flush() and add it immediately after flush().
Now that we know the principle, let’s solve the two problems mentioned at the beginning.3. Solve the problem of stuck output of millions of data in a single page
<?php ob_start(); $data = [1,2,3,4,5,6,7,8,9,10];//实际数据更多,为方便距离假设浏览器一次输出10条会卡死 $per = 3;//每次输出3条,可以改成1000 for ($i = 0;$i < count($data); $i+= $per){ for($j = $i; $j < $i + $per && $j <count($data); $j++){ echo $data[$j]; } ob_flush(); flush(); sleep(2); } echo "Done."; ob_end_flush();4. Solve the problem of stuck when the header implementation file is downloaded because the file is too large
<?php header('Content-type: application/txt');//输出类型 ob_start(); $data = "qwertyuioasdfghjkl";//文件内容,file_get_contents($file) $per = 15;//每次输出15个字符,可以改成1000或更大 for ($i = 0;$i < strlen($data); $i+= $per){ for($j = $i; $j < $i + $per && $j <strlen($data); $j++){ echo $data[$j]; } sleep(2); ob_flush(); flush(); } echo "Done."; ob_end_flush();