笔记:ZipArchive 打包 zip

使用ZipArchive打包文件或文件夹,采用最后一层文件夹目录作为打包文件的根目录:

<?php


namespace App\Service;


class ZipService
{

    public $zipObj;

    public function __construct()
    {
        $this->zipObj = new \ZipArchive();

    }

    /**
     * zip 文件夹打包
     * @param $filePath     | 打包的文件路径
     * @param $zipFileName  | 生成的zip文件路径
     * @return array|bool
     */
    public function createZip($filePath, $zipFileName)
    {
        $zip = $this->zipObj;
        if (!$zip->open($zipFileName, $zip::CREATE)) {
            $msg =  "创建" . $zipFileName . "失败";
            return ['ok' => false, 'msg' => $msg];
        }

        //以最后的文件夹作为打包文件的根路径
        $dirArr = explode(DIRECTORY_SEPARATOR, $filePath);
        $zipFilePath = $dirArr[count($dirArr) - 1] . DIRECTORY_SEPARATOR;
        $this->addFileToZip($filePath, $zip, $zipFilePath);

        $zip->close();
        return true;
    }

    /**
     * zip 文件添加操作
     * @param $filePath     | 打包的文件路径
     * @param $zip          | ZipArchive对象
     * @param $zipRootPath  | zip文件的根目录路径
     */
    function addFileToZip($filePath, $zip, $zipRootPath)
    {
        $handler = opendir($filePath);
        /**
         * 其中 $filename = readdir($handler) 是每次循环的时候将读取的文件名赋值给 $filename,为了不陷于死循环,所以还要让 $filename !== false
         */
        while (($filename = readdir($handler)) !== false) {
            if ($filename != "." && $filename != "..") {
                // 对于文件夹,is_dir会返回TRUE,注意路径是 $newPath
                $newPath = $filePath . DIRECTORY_SEPARATOR . $filename;
                if (is_dir($newPath)) {
                    $nowPath = $zipRootPath . $filename . DIRECTORY_SEPARATOR;
                    $this->addFileToZip($newPath, $zip, $nowPath);
                } else {
                    //文件加入zip对象
                    $zip->addFile($newPath, $zipRootPath . $filename);
                }
            }
        }

        closedir($handler);
    }

}

附:相关php composer包:chumper/zipper

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 1

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!