示例一(用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;
}
?>