笔记:ZipArchive 打包 zip

Laravel框架
404
0
0
2022-05-07
标签   PHP内置库
<?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