探讨如何在PHP开启gzip页面压缩实例
程序员文章站
2022-03-20 08:49:12
示例一(用php的内置压缩函数):复制代码 代码如下:
示例一(用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;
}
?>
复制代码 代码如下:
<?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;
}
?>
上一篇: PHP版 汉字转码的实现详解