php - 在 PHP 中提取 ZIP 文件的子文件夹

标签 php zip unzip

我正在使用 php 脚本解压缩 ZIP 文件。但是这个脚本只解压一级目录而不解压那个文件的子目录 脚本:

$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->extractTo('/my/destination/dir/');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}

例如:如果 test.zip 包含 2 个文件夹:folder1\file.png, folder2\folder3\file3.png

解压缩此 ZIP 文件后,我只看到 folder1*.* 和 folder2*.* 而没有子目录 folder3。

我该如何改进它?

最佳答案

我认为这本 PHP 手册会对您有所帮助 http://php.net/manual/en/ref.zip.php

<?php
$file = "2537c61ef7f47fc3ae919da08bcc1911.zip";
$dir = getcwd();
function Unzip($dir, $file, $destiny="")
{
    $dir .= DIRECTORY_SEPARATOR;
    $path_file = $dir . $file;
    $zip = zip_open($path_file);
    $_tmp = array();
    $count=0;
    if ($zip)
    {
        while ($zip_entry = zip_read($zip))
        {
            $_tmp[$count]["filename"] = zip_entry_name($zip_entry);
            $_tmp[$count]["stored_filename"] = zip_entry_name($zip_entry);
            $_tmp[$count]["size"] = zip_entry_filesize($zip_entry);
            $_tmp[$count]["compressed_size"] = zip_entry_compressedsize($zip_entry);
            $_tmp[$count]["mtime"] = "";
            $_tmp[$count]["comment"] = "";
            $_tmp[$count]["folder"] = dirname(zip_entry_name($zip_entry));
            $_tmp[$count]["index"] = $count;
            $_tmp[$count]["status"] = "ok";
            $_tmp[$count]["method"] = zip_entry_compressionmethod($zip_entry);

            if (zip_entry_open($zip, $zip_entry, "r"))
            {
                $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                if($destiny)
                {
                    $path_file = str_replace("/",DIRECTORY_SEPARATOR, $destiny . zip_entry_name($zip_entry));
                }
                else
                {
                    $path_file = str_replace("/",DIRECTORY_SEPARATOR, $dir . zip_entry_name($zip_entry));
                }
                $new_dir = dirname($path_file);

                // Create Recursive Directory (if not exist)  
                if (!file_exists($new_dir)) {
                  mkdir($new_dir, 0700);
                }

                $fp = fopen($dir . zip_entry_name($zip_entry), "w");
                fwrite($fp, $buf);
                fclose($fp);

                zip_entry_close($zip_entry);
            }
            echo "\n</pre>";
            $count++;
        }

        zip_close($zip);
    }
}
Unzip($dir,$file);
?>

关于php - 在 PHP 中提取 ZIP 文件的子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10968359/

相关文章:

javascript - PHP 用希伯来语创建文件名

javascript - 在 Javascript 中加密并在 Java 中解密 Zip 文件

C# .NET 为什么解压流时需要 Stream.Seek

C++ : Need help on decrypting a zip file and extracting the contents to memory

用于获取 Facebook 点赞的 PHP 代码不再起作用

PHP 查询不起作用

PHP "Remember Me"安全漏洞?

java - 生成一个空的 zip 文件 java

java - 如何在java中将.zip压缩为.gz?

c - 使用 zlib 解压缩 zip 文件