Home php教程 php手册 PHP即时实时输出内容的程序代码

PHP即时实时输出内容的程序代码

May 25, 2016 pm 04:43 PM
Output content

实时输出如果放在js中我们可以直接使用settimeout来守时输入很方便,但是如果在php中实现起来就不能这样了,下面我来给介绍利用 ob_flush() 和 flush()函数实现即时实时输出内容.

一般情况下,PHP都是将整个页面全部执行完成后,才会把要输出的内容发送回客户端,例如如下代码:

for ($i = 0; $i < 10; $i++) { 
    echo $i; 
    sleep(1); 
}
Copy after login

这段代码会在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);
Copy after login

这就用到了PHP的输出控制函数ob_flush()和flush(),我们把代码修改成下面这样,代码如下:

<?php
$str = "Hello world";        
echo $str.str_repeat(&#39; &#39;, 256);        
ob_flush();        
flush();       
sleep(10);   
echo $str;
?>
Copy after login

这段代码则会马上在屏幕上打印 Hello world,关键就在于第2和第3行调用的两个函数 ob_flush() 和 flush(),这两个函数得一起使用才能保证页面马上输出Hello world,其中str_repeat(' ', 256)则是为了解决某些浏览器必须在接收到256个字符后才会显示内容.

对上面函数升级,代码如下:

<?php 
error_reporting(0); 
set_time_limit(0); 
 
$buffer = ini_get(&#39;output_buffering&#39;); 
echo str_repeat(&#39; &#39;,$buffer+1); 
ob_end_flush(); 
 
for($i=1;$i<100;$i++){ 
    echo "$i<br>"; 
    sleep(1); 
    flush(); 
}
?>
Copy after login

这样,页面就会每一秒输出一个数字,我们可以很方便的使用PHP的输出控制来实现页面执行进度的显示,不过,由于PHP页面有执行时间限制,而且长时间执行一个页面会对服务器造成一定的压力.


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24