Compression and Decompression for ZF

With Zend Framework Release 1.10 there will be a way to handle compression and decompression.

The new components Zend_Filter_Compress and Zend_Filter_Decompress provide a unified API for several compression formats.

Actually the formats BZ2, GZ, LZF, RAR, TAR and ZIP are implemented:

You can not only work with Strings, but also with Files and also with complete Directories.
Each format is provided as standalone Adapter. This way we can easily add support for a new compression format by adding a new Adapter.

So let’s go a little bit into details…
To compress a string with BZ2 we would code the following lines:

$filter = new Zend_Filter_Compress('bz2');
$input  = "Uncompressed content";
$output = $filter->filter($input);

$output will have stored the compressed string.
To reverse the output and get the uncompressed string simply do the following:

$filter = new Zend_Filter_Decompress('bz2');
$result = $filter->filter($output);

As you can see compression and decompression is really very simple.

Now when you want to compress and decompress files, it is as simple as compressing strings.
Simply give the filename instead of a string and tell the adapter where to store the archive.

$filter = new Zend_Filter_Compress(array(
    'adapter' => 'bz2'
    'options' => array(
        'archive' => 'myarchive.bz2'
$result = $filter->filter('\\path\to\myfile.ext');

The file myfile.ext will be compressed and stored into myarchive.bz2.
You can even compress complete directories. But be aware, that when you do this on the base directory of your server, your server will be stressed for a very long time.

As you can attach this filters to any component which accepts filters, you could very easily compress any given input to store it anywhere else.

Let’s expect you have a textarea element where your costumer provides a book review. To save space you could easily attach this filter to the element and store the compressed string into the database. When you want to display the content to your user again simply decompress it before rendering.

$element = new Zend_Form_Element_TextArea('myarea');
$element->addFilter('Compress', array('zip'));

There are many places where compression or decompression can be useful. In all this cases you can now use Zend_Filter_Compress.

When you find this component useful feel free to use it within your own application.
Have fun with Zend Framework

Thomas Weidner
I18N Team Leader, Zend Framework

Zend Framework Advisory Board Member
Zend Certified Engineer for Zend Framework

Back to top