Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to compress string in PHP [duplicate]

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.

Is there any way I can compress the string further?

Thanks in advance.

like image 436
MANISH ZOPE Avatar asked Jun 12 '12 05:06

MANISH ZOPE


2 Answers

Im not sure your numbers are right, tho you could use gzdeflate instead of gzcompress as gzcompress adds 6 bytes to the output (2 extra bytes at the beginning and 4 extra bytes at the end).

A simple test shows a 1756800 length string compressed to 99 bytes by double compressing it, 5164 bytes if compressed once.

$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));
like image 153
Lawrence Cherone Avatar answered Oct 25 '22 16:10

Lawrence Cherone


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.

like image 42
Corsair Avatar answered Oct 25 '22 14:10

Corsair