Search code examples
phpzipunzip

Need PHP script to decompress and loop through zipped file


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?


Solution

  • 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') === TRUE) 
    { 
         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!'; 
    }