本文介绍下,用php实现gzip方法压缩html页面的一例代码,有需要的朋友参考下。
代码如下: <?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'); ?> 登录后复制 有兴趣的朋友,可以百度下检测gzip压缩效果的工具或网站,看看压缩比率如何! |