PHP 利用ZipArchive类库实现压缩&解压文件夹

最近有一个小的功能需求,就是需要通过访问接口根据token访问或下载远程的资源压缩包,所以需要实现资源文件夹的压缩及解压,用了很多库最后发现这个类库是比较方便的。

zip文件夹压缩

/**
 * 压缩文件夹
 */
public function createZipFile(){
    $folderPath = public_path("target");
    $zipFilePath = public_path().'/target.zip';
    $zip = new ZipArchive();
    if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
        // 递归添加文件夹下的所有文件和子文件夹
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($folderPath),
            RecursiveIteratorIterator::LEAVES_ONLY
        );
        foreach ($files as $name => $file) {
            if (!$file->isDir()) {
                $filePath = $file->getRealPath();
                $relativePath = substr($filePath, strlen($folderPath) + 1);
                $zip->addFile($filePath, $relativePath);
            }
        }

        $zip->close();
        echo '文件夹压缩成功';
    } else {
        echo '无法打开或创建压缩文件';
    }
}

解压zip压缩包

    /**
 * 网站html解压
 * @param $url
 * @return string
 */
public function websiteHtmlHandle($url)
{
    $pathInfo = pathinfo($url);
    $extension = $pathInfo['extension'];
    //只允许解压zip格式文件
    if (in_array($extension, ["zip"])) {
        try {
            $targetFile = $this->downLoadFile($url);
            $zip = new ZipArchive();
            if ($zip->open($targetFile) === TRUE) {
                $outputFolder = public_path();
                if (!is_dir($outputFolder)) {
                    mkdir($outputFolder, 0777, true);
                }
                // 解压缩文件,保留原文件结构
                $zip->extractTo($outputFolder);
                $zip->close();
                $this->deleteDirectory($targetFile);
            } else {
                return $this->error('解压失败!');
                // 处理打开压缩文件失败的情况
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }else{
        return $this->error('不允许解压改格式压缩包!');
    }
    return  $this->success();
}

看看操作结果:功能没问题。

点赞0
点击评论0
收藏0
浏览 55
 

还没有评论,快来发表第一个评论吧

免责声明:凡在本网站出现的信息,均仅供参考。本网站将尽力确保所提供信息的准确性及可靠性,但不保证有关资料的准确性及可靠性,注册用户和一般页面游览者在使用前请进一步核实,并对任何自主决定的行为负责。本网站对有关资料所引致的错误、不确或遗漏,概不负任何法律责任(包括侵权责任、合同责任和其它责任)
*尊重作者,转载请注明出处!