使用 ZipArchive 打包文件或文件夹,采用最后一层文件夹目录作为打包文件的根目录:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| <?php
namespace App\Service;
class ZipService {
public $zipObj;
public function __construct() { $this->zipObj = new \ZipArchive();
}
public function createZip($filePath, $zipFileName) { $zip = $this->zipObj; if (!$zip->open($zipFileName, $zip::CREATE)) { $msg = "创建" . $zipFileName . "失败"; return ['ok' => false, 'msg' => $msg]; }
$dirArr = explode(DIRECTORY_SEPARATOR, $filePath); $zipFilePath = $dirArr[count($dirArr) - 1] . DIRECTORY_SEPARATOR; $this->addFileToZip($filePath, $zip, $zipFilePath);
$zip->close(); return true; }
function addFileToZip($filePath, $zip, $zipRootPath) { $handler = opendir($filePath);
while (($filename = readdir($handler)) !== false) { if ($filename != "." && $filename != "..") { $newPath = $filePath . DIRECTORY_SEPARATOR . $filename; if (is_dir($newPath)) { $nowPath = $zipRootPath . $filename . DIRECTORY_SEPARATOR; $this->addFileToZip($newPath, $zip, $nowPath); } else { $zip->addFile($newPath, $zipRootPath . $filename); } } }
closedir($handler); }
}
|
附:相关 php composer 包:chumper/zipper
原文链接
https://learnku.com/articles/58662