【问题标题】:How to unzip a zip file that has another zip file inside using PHP如何使用 PHP 解压缩包含另一个 zip 文件的 zip 文件
【发布时间】:2018-08-02 02:25:52
【问题描述】:

我有一个文件 xyz.zip,在这个文件中还有两个文件 test.xml 和另一个 abc.zip 文件包含 test2.xml。当我使用此代码时,它只提取 xyz.zip 文件。但我还需要解压abc.zip

xyz.zip
- test.xml
- abc.zip
- test2.xml

<?php
$filename = "xzy.zip";
$zip = new ZipArchive;
if ($zip->open($filename) === TRUE) {
        $zip->extractTo('./');
        $zip->close();
        echo 'Success!';
}
else {
        echo 'Error!';
}
?>

谁能告诉我如何提取 zip 文件中的所有内容?甚至 abc.zip。这样输出将在一个文件夹中(test.xml 和 test2.xml)。

谢谢

【问题讨论】:

标签: php zip unzip


【解决方案1】:

这可能会对你有所帮助。

此函数将使用 ZipArchive 类展平 zip 文件。

它将提取 zip 中的所有文件并将它们存储在单个目标目录中。也就是说,不会创建子目录。

<?php
// dest shouldn't have a trailing slash
function zip_flatten ( $zipfile, $dest='.' )
{
    $zip = new ZipArchive;
    if ( $zip->open( $zipfile ) )
    {
        for ( $i=0; $i < $zip->numFiles; $i++ )
        {
            $entry = $zip->getNameIndex($i);
            if ( substr( $entry, -1 ) == '/' ) continue; // skip directories

            $fp = $zip->getStream( $entry );
            $ofp = fopen( $dest.'/'.basename($entry), 'w' );

            if ( ! $fp )
                throw new Exception('Unable to extract the file.');

            while ( ! feof( $fp ) )
                fwrite( $ofp, fread($fp, 8192) );

            fclose($fp);
            fclose($ofp);
        }

                $zip->close();
    }
    else
        return false;

    return $zip;
}

/*
How to use:

zip_flatten( 'test.zip', 'my/path' );
*/
?> 

【讨论】:

    【解决方案2】:

    您应该使用递归函数检查所有提取的文件,如果发现其中一个是 zip,则再次调用自身。

    function scanDir($path) {
        $files = scandir($path);
        foreach($files as $file) {
            if (substr($file, -4)=='.zip')
                unzipRecursive($path, $file);
            elseif (isdir($path.'/'.$file))
                scanDir($path.'/'.$file);
        }
    }
    
    function unzipRecursive($absolutePath, $filename) {
        $zip = new ZipArchive;
        $newfolder = $absolutePath.'/'.substr($file, 0, -4);
        if ($zip->open($filename) === TRUE) {
            $zip->extractTo($newfolder);
            $zip->close();
            //Scan the directory
            scanDir($newfolder)
        } else {
            echo 'Error unzipping '.$absolutePath.'/'.$filename;
        }
    }
    

    我没有尝试代码,但我猜它只是为了调试一下

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多