Compress data using gzcompress() in PHP

When working with strings, it is not rare that some are very long. Using the gzcompress() function, strings can be compressed. To uncompressed it, simply call the gzuncompress(). It helps to reduce string size as you can see in below function I am going to demonstrate gzcompress() function to reduce string size which help to optimize your script.

$text =
"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($text);
echo "Original size: ". strlen($string)."<br/>";

echo "Compressed size: ". strlen($compressed)."\n";


$original = gzuncompress($compressed);

In the above example you can see the after using gzcompress() function, string size reduced almost 50% and you can easily get original string back by simply using gzuncompress() in php.

Posted in PHP