教你在PHP ZipArchive解压缩时,去掉zip包里的多余目录层级
推荐:《PHP视频教程》
写了个脚本,下载discuzQ,并解压到指定 git 仓储下,方便更新代码。
遇到一个问题,在解压 uniapp 这个zip包时,里面多了一层目录包装,如果直接解压到指定目录,也会造成多了一级目录,如下图:
那如何从zip包里解压,并去掉多余一层的目录 uniapp_v2.xxxx
,可以看下面的 copy("zip://{$zipFile}#{$filename}", $newFileName);
<?php set_time_limit(0); $config = (object)[ 'zips' => __DIR__ . '/zips', 'uniapp' => __DIR__ . '/uniapp', ]; downloadAndExtract('https://dl.discuz.chat/uniapp_latest.zip', 'uniapp'); function downloadAndExtract($zipUrl, $key) { global $config; echo "正在下载: $zipUrl "; $zipData = file_get_contents($zipUrl); $zipFile = $config->zips . "/$key-" . date('Ymd-His') . '.zip'; file_put_contents($zipFile, $zipData); echo "正在解压到 {$config->$key} "; $zip = new ZipArchive; if ($key === 'uniapp') { 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) === '/') { continue; } // $folder like => uniapp_v2.1.201029/ // $filename like => uniapp_v2.1.201029/commitlint.config.js $newFileName = $config->$key . '/' . str_replace($folder, '', $filename); if (!file_exists(dirname($newFileName))) { mkdir(dirname($newFileName), 0644, true); } copy("zip://{$zipFile}#{$filename}", $newFileName); } $zip->close(); } } echo "-------------- SUCESS -------------- "; }