Last updated on December 10, 2015
In this post I would like to talk about string compression in PHP. There are several algorithms out there which have been designed for specific usage to achieve best results in the compression. Based on the data you need to choose a proper algorithm to achieve better results.
In the below examples we are going to utilize the gzcompress() function to compress string and gzuncompress() function to un-compress string. If you want higher compression rates you can use bzip functions like bzcompress() and bzdecompress().
$string ="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus lobortis, libero vestibulum tincidunt posuere, felis nisi lacinia libero, eu consectetur est libero eu diam. Integer urna urna, venenatis ac lobortis vel, pharetra a neque. Curabitur posuere diam sed tortor aliquam suscipit. Curabitur sodales, tortor vitae consectetur scelerisque, leo nisi laoreet ipsum, sed pellentesque enim dui ac leo. Nam sed porta leo. Nulla at facilisis lacus. Aliquam erat volutpat. Sed nec euismod dolor. Integer dictum magna tempus est blandit aliquet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin at massa nibh, et facilisis sapien. Etiam a justo at urna mattis faucibus a commodo diam. Curabitur sagittis convallis ante, vel laoreet ipsum cursus sed. Nulla eu lectus sem. Pellentesque viverra vulputate tortor, ut semper est viverra in. Mauris est tortor, fringilla a adipiscing non, consequat non eros."; $compressed = gzcompress($string); echo "Original size: ". strlen($string)."\n"; /* prints Original size: 952 */ echo "Compressed size: ". strlen($compressed)."\n"; /* prints -Compressed size: 493 */ // uncompressed - get original string echo gzuncompress($compressed)."\n";