Need PHP script to decompress and loop through zipped file

前端 未结 2 1968
情话喂你
情话喂你 2020-12-19 23:57

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

相关标签:
2条回答
  • 2020-12-20 00:35

    There is a smart way to do it with ZipArchive. You can use a for loop with ZipArchive::statIndex() to get all the information you need. You can access the files by their index (ZipArchive::getFromIndex()) or name (ZipArchive::getFromName()).

    For example:

    function processZip(string $zipFile): bool
    {
        $zip = new ZipArchive();
        if ($zip->open($zipFile) !== true) {
            echo '<p>Can\'t open zip archive!</p>';
            return false;
        }
    
        // As long as statIndex() does not return false keep iterating
        for ($idx = 0; $zipFile = $zip->statIndex($idx); $idx++) {
            $directory = \dirname($zipFile['name']);
    
            if (!\is_dir($zipFile['name'])) {
                // file contents
                $contents = $zip->getFromIndex($idx);
            }
        }
        $zip->close();
    }
    
    0 讨论(0)
  • 2020-12-20 00:36

    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!'; 
    } 
    
    0 讨论(0)
提交回复
热议问题