在 PHP 中压缩字符串的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10991035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to compress string in PHP
提问by MANISH ZOPE
I am compressing the array with gzcompress(json_encode($arr),9). So I am converting array into string with json_encode and then compress with gzcompress. But I could not find the much difference in the size of the resulted string. Before compression size is 488 KB and after compression size is 442 KB.
我正在用 gzcompress(json_encode($arr),9) 压缩数组。所以我使用 json_encode 将数组转换为字符串,然后使用 gzcompress 进行压缩。但是我找不到结果字符串大小的太大差异。压缩前大小为 488 KB,压缩后大小为 442 KB。
Is there any way I can compress the string further?
有什么办法可以进一步压缩字符串吗?
Thanks in advance.
提前致谢。
回答by Lawrence Cherone
Im not sure your numbers are right, tho you could use gzdeflateinstead of gzcompressas gzcompressadds 6 bytes to the output (2 extra bytes at the beginning and 4 extra bytes at the end).
我不确定您的数字是否正确,但您可以使用gzdeflate而不是gzcompressasgzcompress在输出中添加 6 个字节(开头有 2 个额外字节,最后有 4 个额外字节)。
A simple test shows a 1756800 length string compressed to 99 bytes by double compressing it, 5164 bytes if compressed once.
一个简单的测试显示一个长度为 1756800 的字符串通过双重压缩压缩为 99 字节,如果压缩一次则为 5164 字节。
$string = str_repeat('1234567890' . implode('', range('a', 'z')), 48800);
echo strlen($string); //1756800 bytes
$compressed = gzdeflate($string, 9);
$compressed = gzdeflate($compressed, 9);
echo strlen($compressed); //99 bytes
echo gzinflate(gzinflate($compressed));
回答by Corsair
How good the compression of your string will be depends on the data you want to compress. If it consists mainly of random data you won't achieve that much improvements in size. There are many algorithms out there which have been designed for specific usage.
字符串的压缩效果取决于您要压缩的数据。如果它主要由随机数据组成,您将不会在大小上实现那么多改进。有许多算法是为特定用途而设计的。
You should try to determine what your data to compress mainly consists of and then select a proper compression.
您应该尝试确定要压缩的数据主要包括哪些内容,然后选择合适的压缩方式。
Just now I can only refer you to bzcompress, bzip has usually highter compression rates than gzip.
刚才我只能给你推荐 bzcompress, bzip 通常比 gzip 具有更高的压缩率。

