博客 / 詳情

返回

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('打包出錯了,請重試');
    }
}
user avatar chenxiaokai 頭像 mozhong_5eddab49b9d32 頭像 windysay 頭像
3 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.