Zlib / Bzip2
PHP 的 Zlib 和 Bzip2 扩展提供了数据压缩和解压缩功能。Zlib 使用 gzip/deflate 算法,Bzip2 使用 Burrows-Wheeler 压缩算法(通常压缩率更高)。这两个扩展广泛用于 HTTP 内容压缩、数据存储和网络传输。
前置知识
阅读本节前,建议先了解:Zip 扩展
Zlib
zlib 编码/解码
php
<?php
declare(strict_types=1);
// 压缩数据
$data = str_repeat("这是一段需要压缩的文本数据。", 1000);
$compressed = gzencode($data, 9); // gzip 编码(最高压缩级别 1~9)
$deflated = gzdeflate($data, 9); // deflate 原始数据
echo "原始大小: " . strlen($data) . PHP_EOL;
echo "gzip 压缩后: " . strlen($compressed) . PHP_EOL;
echo "deflate 压缩后: " . strlen($deflated) . PHP_EOL;
// 解压缩
$restored = gzdecode($compressed); // gzip 解码
$restored2 = gzinflate($deflated); // inflate 解码
echo "解压后大小: " . strlen($restored) . PHP_EOL;
echo "数据一致: " . ($data === $restored ? 'yes' : 'no') . PHP_EOL;文件压缩
php
<?php
declare(strict_types=1);
// 写入 gzip 文件
$fp = gzopen('/tmp/data.gz', 'w9');
gzwrite($fp, file_get_contents('/path/to/large.log'));
gzclose($fp);
// 读取 gzip 文件
$fp = gzopen('/tmp/data.gz', 'r');
$content = gzread($fp, 4096);
while (!gzeof($fp)) {
$content .= gzread($fp, 4096);
}
gzclose($fp);
// 读取整个 gzip 文件
$content = file_get_contents('compress.zlib:///tmp/data.gz');HTTP gzip 输出
php
<?php
declare(strict_types=1);
// 检测客户端是否支持 gzip
$acceptGzip = str_contains($_SERVER['HTTP_ACCEPT_ENCODING'] ?? '', 'gzip');
if ($acceptGzip) {
ob_start('ob_gzhandler');
}
// ... 输出内容 ...
if ($acceptGzip) {
ob_end_flush();
}Bzip2
php
<?php
declare(strict_types=1);
// 压缩
$data = file_get_contents('/path/to/large.log');
$compressed = bzcompress($data, 9); // 压缩级别 1~9
// 解压
$restored = bzdecompress($compressed);
echo "原始: " . strlen($data) . ", bzip2: " . strlen($compressed) . PHP_EOL;
// 文件操作
$bz = bzopen('/tmp/data.bz2', 'w');
bzwrite($bz, $data);
bzclose($bz);
$bz = bzopen('/tmp/data.bz2', 'r');
$content = bzread($bz, 4096);
while (!feof($bz)) {
$content .= bzread($bz, 4096);
}
bzclose($bz);最佳实践
- Web 输出使用 ob_gzhandler:自动处理 gzip 压缩
- 数据存储使用最高压缩级别:减少磁盘空间
- 网络传输启用压缩:减少带宽消耗
下一节
继续学习:Phar 归档