基本网上找的都是将子文件夹的文件递归出来放入根目录,但我需要保留文件夹本身的结构,终于找到一个自己需要的,修改了一些代码,让该方法可以排除或包含需要的文件
public function test(){ $zip = new \ZipArchive(); $path_zip = $_SERVER['DOCUMENT_ROOT'] . '/Application/Test/testzip/'; $path_files = $_SERVER['DOCUMENT_ROOT'] . '/Application/Test/testPackage/'; if( $zip->open( $path_zip . 'test.zip', \ZipArchive::OVERWRITE ) === true ){ $this->createZip(opendir($path_files),$zip,$path_files, array( array( '1.txt' ), true ) ); $zip->close(); }}/*压缩多级目录 $openFile:目录句柄 $zipObj:Zip对象 $sourceAbso:源文件夹路径 $excludeOrInclude:包含或排除,第一个参数为数组,第二个参数代表方式,不填是包含,为true是排除*/private function createZip($openFile,$zipObj,$sourceAbso, $excludeOrInclude=array() , $newRelat = ''){ while(($file = readdir($openFile)) != false) { if($file=="." || $file=="..") continue; if( $excludeOrInclude ){ if( isset( $excludeOrInclude[0] ) && is_array( $excludeOrInclude[0] ) && $excludeOrInclude[0] ){ //第二的参数为true代表排除,否则代表包含,默认为包含 if( isset( $excludeOrInclude[1] ) && $excludeOrInclude[1] == true ){ if( in_array( $file, $excludeOrInclude[0] ) ){ continue; } }else{ if( ! in_array( $file, $excludeOrInclude[0] ) ){ continue; } } } } /*源目录路径(绝对路径)*/ $sourceTemp = $sourceAbso.'/'.$file; /*目标目录路径(相对路径)*/ $newTemp = $newRelat==''?$file:$newRelat.'/'.$file; if(is_dir($sourceTemp)) { //echo '创建'.$newTemp.'文件夹'; $zipObj->addEmptyDir($newTemp);/*这里注意:php只需传递一个文件夹名称路径即可*/ $this->createZip(opendir($sourceTemp),$zipObj,$sourceTemp,$newTemp); } if(is_file($sourceTemp)) { //echo '创建'.$newTemp.'文件'; $zipObj->addFile($sourceTemp,$newTemp); } }}