教你在PHP ZipArchive解压缩时,去掉zip包里的多余目录层级

推荐:《PHP视频教程》

写了个脚本,下载discuzQ,并解压到指定 git 仓储下,方便更新代码。

遇到一个问题,在解压 uniapp 这个zip包时,里面多了一层目录包装,如果直接解压到指定目录,也会造成多了一级目录,如下图:

Laravel

那如何从zip包里解压,并去掉多余一层的目录 uniapp_v2.xxxx,可以看下面的 copy("zip://{$zipFile}#{$filename}", $newFileName);

<?php

set_time_limit(0);
$config = (object)[
    &#39;zips&#39;    => __DIR__ . &#39;/zips&#39;,
    &#39;uniapp&#39;  => __DIR__ . &#39;/uniapp&#39;,
];

downloadAndExtract(&#39;https://dl.discuz.chat/uniapp_latest.zip&#39;, &#39;uniapp&#39;);

function downloadAndExtract($zipUrl, $key)
{
    global $config;

    echo "正在下载: $zipUrl\n";
    $zipData = file_get_contents($zipUrl);
    $zipFile = $config->zips . "/$key-" . date(&#39;Ymd-His&#39;) . &#39;.zip&#39;;
    file_put_contents($zipFile, $zipData);

    echo "正在解压到 {$config->$key} \n";
    $zip = new ZipArchive;

    if ($key === &#39;uniapp&#39;) {
        if ($zip->open($zipFile) === true) {
            $folder = $zip->getNameIndex(0);
            for ($i = 1; $i < $zip->numFiles; $i++) {
                $filename = $zip->getNameIndex($i);
                if (substr($filename, -1, 1) === &#39;/&#39;) {
                    continue;
                }

                // $folder like => uniapp_v2.1.201029/
                // $filename like => uniapp_v2.1.201029/commitlint.config.js
                $newFileName = $config->$key . &#39;/&#39; . str_replace($folder, &#39;&#39;, $filename);
                if (!file_exists(dirname($newFileName))) {
                    mkdir(dirname($newFileName), 0644, true);
                }
                copy("zip://{$zipFile}#{$filename}", $newFileName);
            }
            $zip->close();
        }
    } 

    echo "-------------- SUCESS --------------\n";
}

以上就是教你在PHP ZipArchive解压缩时,去掉zip包里的多余目录层级的详细内容,更多请关注其它相关文章!