下面的代碼成功創建了指定目錄和所有子目錄的 zip 文件。我遇到的問題是最終結果從根目錄中的每個文件名和文件夾名中刪除了第一個字符;同樣的行為不會發生在子目錄中。<?php require('../config/config.php'); $rootPath = $abs_path.'/includes/qrcodes/'; // SOURCE FOLDER TO ZIP $zipFilename = 'qr_images.zip'; $zip = new ZipArchive(); $zip->open($zipFilename, ZipArchive::CREATE | ZipArchive::OVERWRITE); $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY); foreach ($files as $name => $file) { $filePath = $file->getRealPath(); $relativePath = substr($filePath, strlen($rootPath) + 1); if (!$file->isDir()) { $zip->addFile($filePath, $relativePath); }else { if($relativePath !== false) $zip->addEmptyDir($relativePath); } } $zip->close(); ?>目前生成的 zip 文件包括:再見(文件夾)radio_1.pngradio_2.pngnfosys(文件夾)infosys_1.pngehicles(文件夾)vehicle_1.pngvehicle_2.png這些文件夾應命名為“radios”、“infosys”和“vehicles”。
1 回答

慕容3067478
TA貢獻1773條經驗 獲得超3個贊
該代碼似乎是為沒有結尾反斜杠的 $rootpath 變量設計的。如果您要更改它,$rootPath = $abs_path.'/includes/qrcodes';
則需要 substr 處的 +1。否則,相對路徑將以“/”開頭。
- 1 回答
- 0 關注
- 144 瀏覽
添加回答
舉報
0/150
提交
取消