Home > Article > Backend Development > Teach you how to remove redundant directory levels in the zip package when decompressing PHP ZipArchive
Recommended: "PHP Video Tutorial"
Write a script to download discuzQ and extract it to the specified git repository to facilitate updating the code.
I encountered a problem. When decompressing the uniapp zip package, there is an extra layer of directory packaging. If you decompress it directly to the specified directory, it will also cause an extra level of directory, as shown below:
Then how to unzip the zip package and remove the extra layer of directories uniapp_v2.xxxx
, you can see the following 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\n"; $zipData = file_get_contents($zipUrl); $zipFile = $config->zips . "/$key-" . date('Ymd-His') . '.zip'; file_put_contents($zipFile, $zipData); echo "正在解压到 {$config->$key} \n"; $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 --------------\n"; }
The above is the detailed content of Teach you how to remove redundant directory levels in the zip package when decompressing PHP ZipArchive. For more information, please follow other related articles on the PHP Chinese website!