Home > php教程 > php手册 > body text

php ob_start(ob_gzhandler)进行网页压缩

WBOY
Release: 2016-06-13 09:47:44
Original
1301 people have browsed it

本文章来总结关于php ob_start(ob_gzhandler)进行网页压缩传输的实现有需要的朋友可参考一下。

先来看ob_start用法

使用PHP ob_start()函数打开browser的cache,这样可以保证cache的内容在你调用flush(),ob_end_flush()(或程序执行完毕)之前不会被输出

 代码如下 复制代码

ob_start(); //打开缓冲区  
phpinfo(); //使用phpinfo函数  
$info=ob_get_contents(); //得到缓冲区的内容并且赋值给$info  
$file=fopen(’info.txt’,'w’); //打开文件info.txt  
fwrite($file,$info); //写入信息到info.txt  
fclose($file); //关闭文件info.txt  

?> 

PHP ob_start()函数一个很大的特点;也可以使用ob_start的参数,在cache被写入后,然后自动运行命令,比如ob_start(”ob_gzhandler”);而我们最常用的做法是用ob_get_contents()得到cache中的内容

面的代码是一个压缩网页的例子,我 们利用ob_gzip函数,使用ob_start将输出内容压缩后放到“缓冲区”后再输出。

 代码如下 复制代码

//启用压缩   
if(function_exists('ob_gzip'))   
{   
   ob_start('ob_gzip');   
}   
//准备一些待压缩的内容   
for($i=0; $i {   
    echo('这里是测试内容
');   
}   
//输出压缩成果   
ob_end_flush();   
  
  
//这是ob_gzip压缩函数   
function ob_gzip ($content)   
{   
    if( !headers_sent()  && extension_loaded ("zlib")  && strstr ( $_SERVER["HTTP_ACCEPT_ENCODING"], "gzip")){   
        $content = gzencode($content,9);   
        header ("Content- Encoding: gzip");   
        header ("Vary: Accept- Encoding");   
        header ("Content- Length: ".strlen ($content));   
    }   
    return ($content) ;   
}

source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!