关于php:php-打包-zip

php 应用原生的 ZipArchive 类来打包 zip。

<?php

namespace App\Services;

use Exception;
use Illuminate\Support\Facades\Log;

/**
 * Class Zip
 *
 * @package App\Services
 */
class Zip
{
    /**
     * @param  array   $path_arr 待打包的文件门路汇合
     * @param  string  $zip_path 压缩包门路
     *
     * @return string
     */
    public static function makeZip(array $path_arr, string $zip_path): string
    {
        $zip = new \ZipArchive();
        try {
            if ($zip->open($zip_path, \ZipArchive::CREATE | \ZipArchive::OVERWRITE)) {
                foreach ($path_arr as $file) {
                    if (!file_exists($file)) {
                        continue;
                    }
                    $zip->addFile($file, basename($file));
                }
                $zip->close();
                return $zip_path;
            }
        } catch (\Throwable $e) {
            Log::error(sprintf("%s err %s", __METHOD__, $e->getMessage()));
            throw new Exception('打包出错了,请重试');
        }
        
        throw new Exception('打包出错了,请重试');
    }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理