環境準備
- 開啟
php_zip.dll(Windows)或 zlib(Linux)擴展
- 修正
php.ini 中 extension_dir 路徑,重啟 Web 服務

核心代碼
$filename = date("YmdHis");
$zip = new ZipArchive();
$zip->open($filename . ".zip", ZipArchive::OVERWRITE);
foreach ($data as $val) {
$attachfile = "E:\\bysj\\bysj" . $val['fileaddr'] . $val['filename'];
$attachfile = iconv("UTF-8", "GBK", $attachfile); // 關鍵:中文路徑轉編碼
$zip->addFile($attachfile, basename($attachfile));
}
$zip->close();
// 輸出下載
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=" . basename($filename) . ".zip");
header("Content-Length: " . filesize($filename . ".zip"));
readfile($filename . ".zip");
關鍵點總結
iconv("UTF-8","GBK",...) 解決中文文件名壓縮亂碼/失敗
- 設置完整 HTTP Header 確保瀏覽器正確下載
- 臨時 zip 文件下載後建議定時清理