Wednesday, November 11, 2009

PHP: How to read a GZip file


Share at Facebook

I was trying to read a gzip file using PHP. But I found it was a bit hard, and I waste a lot of times for this. I was trying the Zlib library of PHP. But damn! it wasn't working to read a GZip file.

First I tried to read the file as binary mode, and then passed the whole content to the function gzuncompress(), but it was getting error. Failed to parse kinda error. When I was pissed off, I tried with other deflate/inflate functions, but all were suck.

Later one of my friend suggested me to to read the file as gzip data using gzfile(), and it worked for me. It worked for me. Just a one line code that solved my problem, and I was scratching my head to find it at google. Here is the code.


$__GZIP_FILE = "my_gzip_file.gz";
$file_data = implode("", gzfile($__GZIP_FILE));
echo $file_data;


That's it. It will read your gzip file, and return the whole uncompressed content into the variable. So simple, but so hard if you don't know the right way ;-)




No comments: