Home  >  Article  >  Backend Development  >  Teach you how to remove redundant directory levels in the zip package when decompressing PHP ZipArchive

Teach you how to remove redundant directory levels in the zip package when decompressing PHP ZipArchive

藏色散人
藏色散人forward
2020-11-01 15:34:566556browse

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:

Teach you how to remove redundant directory levels in the zip package when decompressing PHP ZipArchive

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)[
    &#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";
}

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!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete