【问题标题】:ZipArchive::addFile() creates zip files with tree structure in Windows but flattened in LinuxZipArchive::addFile() 在 Windows 中创建树形结构的 zip 文件,但在 Linux 中是扁平的
【发布时间】:2021-12-07 19:22:59
【问题描述】:

我使用 PHP 的 ZipArchive 库创建了一个 zip 文件,以便轻松地将某些电子商店同步服务的图像从桌面传输到电子商店的 Web 服务器。我用来创建 zip 的脚本如下:

function compress(string $path)
{
    $zip = new ZipArchive();
    $zip->open(dirname(SOURCE_PATH, 1) . '\\' . explode('\\', SOURCE_PATH)[count(explode('\\', SOURCE_PATH)) - 2] . '.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE); // Some path manipulation here, to actually take the whole "parent" folder of the path passed to the function's parameter

    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::LEAVES_ONLY);

    foreach ($files as $file) {
        if (!$file->isDir()) {
            $real = $file->getRealPath();
            $relative = substr($real, strlen($path));

            $zip->addFile($real, $relative);
        }
    }

    $zip->close();
}

我的问题是,当您在 WinRAR 中查看 zip 的内容时,它们在文件夹中正常显示;当您提取 zip 文件时,将再次构建整个文件夹树以及文件。但是当你将zip文件传输到托管e-shop的linux服务器并解压时,文件都被解压到了zip上传的文件夹中,好像zip文件被“扁平化”了......

请观看以下两个视频:

Windows

Linux

我做错了什么?这是我第一次使用 ZipArchive,所以我没有太多经验。

【问题讨论】:

    标签: php ziparchive


    【解决方案1】:

    zip中的文件路径必须使用/作为路径分隔符,你可以试试下面的代码

    function compress(string $path)
    {
        $zip = new ZipArchive();
        $zip->open(dirname(SOURCE_PATH, 1) . '\\' . explode('\\', SOURCE_PATH)[count(explode('\\', SOURCE_PATH)) - 2] . '.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE); // Some path manipulation here, to actually take the whole "parent" folder of the path passed to the function's parameter
    
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::LEAVES_ONLY);
    
        foreach ($files as $file) {
            if (!$file->isDir()) {
                $real = $file->getRealPath();
                $relative = substr($real, strlen($path));
                // replace path separator
                $relative = str_replace('\\', '/', $relative);
                $zip->addFile($real, $relative);
            }
        }
    
        $zip->close();
    }
    

    【讨论】:

    • 你说的太对了!确实这就是问题所在!非常非常非常感谢! :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    相关资源
    最近更新 更多