Home >Backend Development >PHP Tutorial >PHP method to implement web page compression function based on ob_start(ob_gzhandler)
This article mainly introduces how PHP implements web page compression function based on ob_start('ob_gzhandler'), involving ob_gzip, ob_start and other functions in PHP to operate the buffer and content compression related techniques. Friends in need can refer to the following
The example in this article describes how PHP implements web page compression function based on ob_start('ob_gzhandler'). Share it with everyone for your reference, the details are as follows:
PHP generates a web page and sends it to the browser for display. In addition to the user's Internet speed, the opening speed of the page is often closely related to the size of the page. We can Start with web page size to improve web page responsiveness.
The following code is an example of compressing a web page. We use the ob_gzip function and ob_start to compress the output content and put it into the "buffer" before outputting it.
PHP code
//启用压缩 if(function_exists('ob_gzip')) { ob_start('ob_gzip'); } //准备一些待压缩的内容 for($i=0; $i<100; $i++) { echo('这里是测试内容 <br>'); } //输出压缩成果 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) ; }
How effective is it? Here I tested the above code.
Before compression:
After compression:
More php based on ob_start(ob_gzhandler) For related articles on how to implement web page compression function, please pay attention to the PHP Chinese website!