Apache Web 服务器替代方案
首先,如果您使用Apache Web Server,您可能需要启用和配置mod_deflate。它将在将内容发送到客户端之前处理内容压缩。
PHP 替代方案 #1
如果没有,那么您可以使用ob_gzhandler (PHP 4 >= 4.0.4, PHP 5) 来激活 gzip 输出缓冲区。
if(!ob_start("ob_gzhandler")) ob_start();
echo $json;
PHP 替代方案 #2
如果这些内容更多地以未压缩格式使用,另一种可能性(未测试)可能是将内容缓存在磁盘上,而不是将 gzip 内容放入数据库中。使用gzencode。
$json = array('id' => $id, 'content' => $content);
$file = '/tmp/' . $json['id'] . '.json';
if(!file_exists($file)) {
$gzip = gzencode($json['content']);
file_put_contents($file, $gzip);
} else {
$gzip = file_get_contents($file);
}
header('Content-Encoding: gzip');
header('Content-Length: '.strlen($gzip));
echo $gzip;
这种方式可能只适用于输出 gzip 压缩的内容,它可能不适用于所有浏览器。
PHP 替代方案 #2.5
仅当浏览器接受时从磁盘缓存中输出 gzip 压缩的内容。
$json = array('id' => $id, 'content' => $content);
if( strpos($_SERVER["HTTP_ACCEPT_ENCODING"],'gzip') !== false ) {
$file = '/tmp/' . $json['id'] . '.json';
if(!file_exists($file)) {
$gzip = gzencode($json['content']);
file_put_contents($file, $gzip);
} else {
$gzip = file_get_contents($file);
}
header('Content-Encoding: gzip');
header('Content-Length: '.strlen($gzip));
echo $gzip;
} else {
echo $json['content'];
}