Compressing data

at 2010-01-06 in Examples by friebe (0 comments)

The possibly easiest way to compress data in PHP is to use the string-in, string-out functions such as gzdeflate or bzcompress. For small number of bytes being passed in, this is fast and convenient, but it doesn't do well when working with large files, for example:

<?php 
FileUtil::setContents
(
$out,
gzdeflate
(FileUtil::getContents($in))
);
?>
In one test I ran here, this piece of code used roughly 50MB peaks to compress a 26 MB input file. As of 5.7.7, the XP Framework will provide compressing output streams enabling you to compress one chunk at a time and saving more than 90% of memory:
<?php 
$is= $in->getInputStream();
$os= new DeflatingOutputStream($out->getOutputStream());
while
($is->available() > 0) {
$os->write($is->read());
}
$is->close();
$os->close();
?>
Sure, this is more code, but it constantly uses not more than 0.5 MB while running. If you now have a look at the new io.streams.StreamTransfer class you can simplify the above code even more (and still save the memory).



Subscribe

You can subscribe to the XP framework's news by using RSS syndication.


Categories

News
General
PHP5
Announcements
RFCs
Further reading
Examples
Editorial
EASC
Experiments
Unittests
Databases
5.8-SERIES

Related

Find related articles by a search for «Compressing».