实时输出如果放在js中我们可以直接使用settimeout来守时输入很方便,但是如果在php中实现起来就不能这样了,下面我来给介绍利用 ob_flush() 和 flush()函数实现即时实时输出内容.
一般情况下,PHP都是将整个页面全部执行完成后,才会把要输出的内容发送回客户端,例如如下代码:
for ($i = 0; $i < 10; $i++) { echo $i; sleep(1); }
这段代码会在10秒钟后一次性输出"0123456789",对于运行时间较长的PHP程序来说可能都需要即时输出内容来查看运行情况,代码如下:
header("Content-type:text/html;charset=utf-8"); //设置执行时间不限时,代码如下: set_time_limit(0); //清除并关闭缓冲,输出到浏览器之前使用这个函数,代码如下: ob_end_clean(); //控制隐式缓冲泻出,默认off,打开时,对每个 print/echo 或者输出命令的结果都发送到浏览器,代码如下: ob_implicit_flush(1);
这就用到了PHP的输出控制函数ob_flush()和flush(),我们把代码修改成下面这样,代码如下:
<?php $str = "Hello world"; echo $str.str_repeat(' ', 256); ob_flush(); flush(); sleep(10); echo $str; ?>
这段代码则会马上在屏幕上打印 Hello world,关键就在于第2和第3行调用的两个函数 ob_flush() 和 flush(),这两个函数得一起使用才能保证页面马上输出Hello world,其中str_repeat(' ', 256)则是为了解决某些浏览器必须在接收到256个字符后才会显示内容.
对上面函数升级,代码如下:
<?php error_reporting(0); set_time_limit(0); $buffer = ini_get('output_buffering'); echo str_repeat(' ',$buffer+1); ob_end_flush(); for($i=1;$i<100;$i++){ echo "$i<br>"; sleep(1); flush(); } ?>
这样,页面就会每一秒输出一个数字,我们可以很方便的使用PHP的输出控制来实现页面执行进度的显示,不过,由于PHP页面有执行时间限制,而且长时间执行一个页面会对服务器造成一定的压力.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!
