簡體   English   中英

如何使用PHP解壓縮其中包含另一個zip文件的zip文件

[英]How to unzip a zip file that has another zip file inside using PHP

我有一個文件xyz.zip ,在此文件中還有兩個文件test.xml和另一個包含test2.xml的 abc.zip文件。 當我使用此代碼時,它僅提取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)。

謝謝

這可能對您有幫助。

此函數將使用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' );
*/
?> 

您應該使用一個遞歸函數來檢查所有提取的文件,如果發現其中一個是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;
    }
}

我沒有嘗試代碼,但只是調試了一下

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM