时间:2021-07-01 10:21:17 帮助过:20人阅读
输出
function ob_gzip($content) // $content 就是要压缩的页面内容,或者说饼干原料
{
if( !headers_sent() && // 如果页面头部信息还没有
输出压缩成果
<?php
//启用一个带有ob_gzip压缩机的工作台
ob_start('ob_gzip');
//准备一些待压缩的内容
for($i=0; $i<100; $i )
{
echo('这里是压缩饼干的原料,这里是压缩饼干的原料,原料');
}
//
Fri Jan 25 17:53:10 2008 HTTP/1.1 200 OK
Fri Jan 25 17:53:10 2008 Server: Microsoft-IIS/5.1
Fri Jan 25 17:53:10 2008 Date: Fri, 25 Jan 2008 09:53:10 GMT
Fri Jan 25 17:53:10 2008 Connection: close
Fri Jan 25 17:53:10 2008 X-Powered-By: PHP/5.2.5
Fri Jan 25 17:53:10 2008 Content-Encoding: gzip
Fri Jan 25 17:53:10 2008 Vary: Accept-Encoding
Fri Jan 25 17:53:10 2008 Content-Length: 104
Fri Jan 25 17:53:10 2008 Content-type: text/html
示例一(用php的内置压缩函数):
代码如下:
<?PHP
if(Extension_Loaded('zlib')) Ob_Start('ob_gzhandler');
Header("Content-type: text/html");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>
<body>
<?php
for($i=0;$i<10000;$i++){
echo 'Hello World!';
}
?>
</body>
</html>
<?PHP
if(Extension_Loaded('zlib')) Ob_End_Flush();
?>
示例二(自写函数):
代码如下:
<?php ob_start('ob_gzip'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>
<body>
</body>
</html>
<?php
ob_end_flush();
//压缩函数
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;
}
?>