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
相关产品推荐
相关产品推荐

