php压缩字符串的函数

发布时间:2020-01-05编辑:脚本学堂
php压缩字符串的函数

使用PHP可以对字符串进行压缩,但不涉及任何压缩文件。
下面的例子,使用 gzcompress() 和 gzuncompress() 函数:
 

复制代码 代码如下:

$string =
"Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nunc ut elit id mi ultricies
adipiscing. Nulla facilisi. Praesent pulvinar,
sapien vel feugiat vestibulum, nulla dui pretium orci,
non ultricies elit lacus quis ante. Lorem ipsum dolor
sit amet, consectetur adipiscing elit. Aliquam
pretium ullamcorper urna quis iaculis. Etiam ac massa
sed turpis tempor luctus. Curabitur sed nibh eu elit
mollis congue. Praesent ipsum diam, consectetur vitae
ornare a, aliquam a nunc. In id magna pellentesque
tellus posuere adipiscing. Sed non mi metus, at lacinia
augue. Sed magna nisi, ornare in mollis in, mollis
sed nunc. Etiam at justo in leo congue mollis.
Nullam in neque eget metus hendrerit scelerisque
eu non enim. Ut malesuada lacus eu nulla bibendum
id euismod urna sodales. ";

$compressed = gzcompress($string);

echo "Original size: ". strlen($string)."n";
/* prints
Original size: 800
*/

echo "Compressed size: ". strlen($compressed)."n";
/* prints
Compressed size: 418
*/

// getting it back
$original = gzuncompress($compressed);

压缩率可以达到 50% 左右。
另外,函数 gzencode() 和 gzdecode() 也可以达到类似结果,只是通过使用不同的压缩算法实现而已。