tags:

views:

33

answers:

2

I am using a fairly straight-forward script to open and parse several xml files that are gzipped. I also need to do the same basic operation with a ZIP file. It seems like it should be simple, but I haven't been able to find what looked like equivalent code anywhere.

Here is the simple version of what I am already doing:

$import_file = "source.gz";

$sfp = gzopen($import_file, "rb");  /////  OPEN GZIPPED data
while ($string = gzread($sfp, 4096)) {    //Loop through the data

    /// Parse Output And Do Stuff with $string
}
gzclose($sfp);      

What would do the same thing for a zipped file?

A: 

Maybe you can use this library - ZZIPLib

Here is example - http://www.timlinden.com/blog/website-development/unzip-files-with-php/

Ivo Sabev
+2  A: 

If you have PHP 5 >= 5.2.0, PECL zip >= 1.5.0 then you may use the ZipArchive libraries:

$zip = new ZipArchive; 
if ($zip->open('source.zip')) 
{ 
     for($i = 0; $i < $zip->numFiles; $i++) 
     {   
        $fp = $zip->getStream($zip->getNameIndex($i));
        if(!$fp) exit("failed\n");
        while (!feof($fp)) {
            $contents = fread($fp, 8192);
            // do some stuff
        }
        fclose($fp);
     }
} 
else 
{ 
     echo 'Error reading zip-archive!'; 
} 
thetaiko
Thanks thetaiko. I will try it right away. -Jim
Jim H.
thetaiko - This does exactly what I need. Thanks. You need to correct two small errors, however. The closign bracket for the "for" loop is missing, and fread also requires a length parameter. Fix those two and it runs like a charm. Will it work on HTTP and FTP connections also? If so, can you pass username and password to it also. Thanks again, Jim
Jim H.
Hm, not sure exactly what you mean by it workin on HTTP and FTP connections. I would suppose that you can pass it any path but I haven't tried it. Instead of passing 'source.zip' to `$zip->open()`, try this: `$zip->open('http://some.url.com/source.zip');`
thetaiko
I will try it when I have a chance. If it works my next question would be how to pass the username and password when you wanted to connect via ftp. But my guess is that it doesn't allow this. It would make my life too easy.
Jim H.
Actually, I think that you can usually pass the username and password like this: `ftp://username:[email protected]/path`
thetaiko