Recipe 23.22. Reading and Writing Compressed Files


23.22.1. Problem

You want to read or write compressed files.

23.22.2. Solution

Use the compress.zlib or compress.bzip2 stream wrapper with the standard file functions. Example 23-57 reads data from a gzip-compressed file.

Reading a compressed file

<?php $fh = fopen('compress.zlib://lots-of-data.gz','r') or die("can't open: $php_errormsg"); while ($line = fgets($fh)) {     // $line is the next line of uncompressed data } fclose($fh) or die("can't close: $php_errormsg"); ?>

23.22.3. Discussion

The compress.zlib stream wrapper provides access to files that have been compressed with the gzip algorithm. The compress.bzip2 stream wrapper provides access to files that have been compressed with the bzip2 algorithm. Both stream wrappers allow reading, writing, and appending with compressed files. To enable the zlib and bzip2 compression streams, build PHP with --withzlib and --with-bz2, respectively.

In addition to the stream wrappers, which allow access to compressed local files, there are stream filters that compress (or uncompress) arbitrary streams on the fly. The zlib.deflate and zlib.inflate filters compress and uncompress data according to the zlib "deflate" algorithm. The bzip2.compress and bzip2.uncompress filters do the same for the bzip2 algorithm.

Each stream filter must be applied to a stream after it is created. Example 23-58 uses the bzip2 stream filters to read compressed data from a URL.

Reading compressed data from a URL

<?php $fp = fopen('http://www.example.com/something-compressed.bz2','r'); stream_filter_append($fp, 'bzip2.uncompress'); while (! feof($fp)) {     $data = fread($fp);     // do something with $data; } fclose($fp); ?>

23.22.4. See Also

Documentation on compression stream wrappers at http://www.php.net/wrappers.compression, on compression filters at http://www.php.net/filters.compression, and on stream_filter_append( ) at http://www.php.net/stream_filter_append; the zlib algorithm is detailed in RFCs 1950 (http://www.faqs.org/rfcs/rfc1950.html) and 1951 (http://www.faqs.org/rfcs/rfc1951.html).




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net