PHP code to implement gzip compression of html data

WBOY
Release: 2016-07-25 08:57:21
Original
985 people have browsed it
This article introduces an example code that uses PHP to implement gzip method to compress HTML pages. Friends in need can refer to it.

The code is as follows:

<?php
/**
* gzip压缩html数据
* edit by bbs.it-home.org
*/
 ob_start("ob_gzhandler");  
 ob_start("compress");  //开启压缩
 
 header("Content-type: text/Css; charset: UTF-8");  
 header("Cache-Control: must-revalidate");  
 $off = 0; # Set to a reaonable value later, say 3600 (1 hr);  
 $exp = "Expires: " . gmdate("D, d M Y H:i:s", time() + $off) . " GMT";  
 
 header($exp);  
   
function compress($buffer) {  
     $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); // remove comments  
     $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer); // remove tabs, spaces, newlines, etc.  
     $buffer = str_replace('{ ', '{', $buffer); // remove unnecessary spaces.  
     $buffer = str_replace(' }', '}', $buffer);  
     $buffer = str_replace('; ', ';', $buffer);  
     $buffer = str_replace(', ', ',', $buffer);  
     $buffer = str_replace(' {', '{', $buffer);  
     $buffer = str_replace('} ', '}', $buffer);  
     $buffer = str_replace(': ', ':', $buffer);  
     $buffer = str_replace(' ,', ',', $buffer);  
     $buffer = str_replace(' ;', ';', $buffer);  
     return $buffer;  
 }  
   
require_once('screen.css');  
require_once('layout.css');  
require_once('custom.php');  
require_once('titles.css');  
require_once('bus.css');   
?>
Copy after login

For those who are interested, you can download tools or websites that detect gzip compression effects on Baidu to see what the compression ratio is!



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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template