You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中ZipArchive每次生成含旧文件,如何创建空压缩包?

解决ZipArchive生成重复文件的问题

问题核心在于你使用ZipArchive::CREATE打开文件时,若目标Zip文件已经存在,PHP会追加内容到已有文件,而不是清空重建,这就是每次运行都包含之前文件的原因,添加空目录的操作无法覆盖已有内容。

两种可行解决方案:

  • 方案一:先删除已有Zip文件再创建
    在打开Zip文件前,先检查并删除已存在的文件,确保每次都是从空开始:

    // 先删除已存在的zip文件
    if (file_exists($zipName)) {
        unlink($zipName);
    }
    
    // 再创建新的zip
    $zip = new ZipArchive;
    $zip->open($zipName, ZipArchive::CREATE);
    
  • 方案二:使用ZipArchive::OVERWRITE模式
    直接使用覆盖模式打开文件,若文件存在则清空覆盖,不存在则自动创建,这是更简洁的方式:

    $zip = new ZipArchive;
    // OVERWRITE模式:存在则覆盖,不存在则创建
    $zip->open($zipName, ZipArchive::OVERWRITE);
    

修改后的完整示例代码

// open zip - 使用OVERWRITE模式确保从空开始
$zip = new ZipArchive;
$zip->open($zipName, ZipArchive::OVERWRITE);

// add pdfs to zip file
foreach($arPDFs as $thisPDF) {
    $pdfPath = config('path')['scTemp'] . $thisPDF;
    if (File::exists($pdfPath)) {
        $zip->addFile($pdfPath, $thisPDF);
    }
}

// close zip
$zip->close();

// delete all pdfs
foreach($arPDFs as $thisPDF) { 
    $pdfPath = config('path')['scTemp'] . $thisPDF;
    if (File::exists($pdfPath)) {
        File::delete($pdfPath);
    }
}

// download zip file
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipName);
header('Content-Length: '.filesize($zipName));
readfile($zipName);

内容的提问来源于stack exchange,提问作者Paul Godard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 18:27:44