需要PHP脚本来解压缩并循环压缩压缩文件

时间:2010-04-08 13:20:53

标签: php zip unzip

我使用一个相当简单的脚本来打开和解析几个gzip压缩的xml文件。我还需要使用ZIP文件执行相同的基本操作。看起来它应该很简单,但我无法在任何地方找到看起来像等效的代码。

这是我正在做的简单版本:

$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);      

压缩文件会做同样的事情吗?

2 个答案:

答案 0 :(得分:4)

如果你有PHP 5> = 5.2.0,PECL zip> = 1.5.0那么你可以使用ZipArchive库:

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

答案 1 :(得分:0)

有一种使用ZipArchive的聪明方法。您可以对for使用ZipArchive::statIndex()循环来获取所需的所有信息。您可以按文件的索引(ZipArchive::getFromIndex())或名称(ZipArchive::getFromName())访问文件。

例如:

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();
}
相关问题