Need PHP script to decompress and loop through zipped file

耗尽温柔 提交于 2019-12-29 08:03:39

问题


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?


回答1:


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!'; 
} 


来源:https://stackoverflow.com/questions/2600105/need-php-script-to-decompress-and-loop-through-zipped-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!