PHP and compression/archiving, with examples
Posted by: Floresense Team
Using bZip2: This library's core comes from: http://www.bzip.org/ bZip and bZip2 are just different types or versions of the same format. Know more about the differences at bzip.org
This library will help us create/read .bz2 files. Like gzip, bzip is not an archiving format, only a compression format, and to bzip a group of files you can first tar it and then bzip the single .tar file to make .tar.bzip2 Again, .tar.bzip or .tar.bzip2 files are very common in packaging software for linux.
This library is not enabled by default in PHP.
Library file: php_bz2.dll Install Type: PHP extension.
Creating a .bz compressed file
$filename = "test.bz";
// open file for writing $bz = bzopen($filename, "w"); // write string to file bzwrite($bz, $str); // close file bzclose($bz);
Reading a .bz compressed file
$bz = bzopen($filename, "r");
// read all while (!feof($bz)) { $contents .= bzread($bz, 4096); }
// output. echo $contents;
bzclose($bz);
Using LZF:
LZF is a very fast compression algorithm.. best suited for saving little storage space by saving all user content/preferences/data in LZF compressed format and read on-the-fly when such data is used.
This library is not enabled by default in PHP.
Library file: php_lzf.dll Install Type: PHP extension.
LZF support in PHP enables only two core methods.. for compressing and decompressing a string. Obviously, we can then write the compressed string into a file or a database record or cookie or however suitable.
The methods are lzf_compress($inputString), and lzf_decompress($inputCompressedString)
$test3 = lzf_compress($testString);
Best compression:
Similar compression and decompression methods for strings are available on gz and bz2 libraries also. Below example tries to find out what compresses best with default settings..
$testString = "The primary awareness is to make people understand that Right to Education is a basic right of every child irrespective of the social status. It is also to highlight the importance of public participation so as to bring in a change. We try to bring about basic awareness about the RTE act, i.e., basic contents of the act and what right it ensures to "all" the children of India, the ground reality as opposed to what the government and constitution assures, and hence the disparity."; $test = bzcompress($testString,9); $test2 = gzcompress($testString,9); $test3 = lzf_compress($testString); echo "*".strlen($testString)."*".strlen($test)."*".strlen($test2)."*".strlen($test3);
As can be expected, the compression algorithms are sensitive to content... most algorithms compress better if the string has too much repititive characters or words.
Advertisement
|