$path = PUBLIC_DIR.'/images/'; //待压缩文件夹父目录 $zipPath = PUBLIC_DIR.'/images_zip/'; //压缩文件保存目录 !is_dir($zipPath) ? mkdir($zipPath, 0755, true) : ''; // Initialize archive object $zip = new ZipArchive(); $dir_list = scandir($path); if (empty($dir_list)) { return false; } foreach($dir_list as $dir_name) { if ($dir_name == '.' || $dir_name == '..') { continue; } $dir_path = $path.$dir_name; //待压缩目录 if (!is_dir($dir_path)) { continue; } $zipFile = $zipPath.$dir_name.'.zip'; //压缩包名称 $zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE); $file_list = scandir($dir_path); //文件名 foreach ($file_list as $file_name) { if ($file_name == '.' || $file_name == '..') { continue; } $zip->addFile($dir_path.'/'.$file_name, $file_name); //第二个参数使压缩文件名为待压缩文件原名(否则压缩包里会有多级目录) } $zip->close(); }
待压缩文件夹:
压缩后压缩包:
打开压缩包看效果: