php利用ZipArchive类操作文件的实例
ZipArchive类是专门用于文件的压缩与解压操作的类,通过压缩文件可以达到节省磁盘空间的目的,并且压缩文件体积更小,便于网络传输。
function filestozip($fileList,$filename=''){ if(empty($fileList))return false; if(empty($filename))$filename=time().'.zip'; $filename = "/uploads/temp/".$filename; // 压缩包所在的位置路径 if(file_exists($filename))return $filename; $zip = new \ZipArchive(); $zip->open($filename,\ZipArchive::CREATE); //打开压缩包 foreach($fileList as $file){ if(substr($file,0,4)=='http'){ $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 0); curl_setopt($ch,CURLOPT_URL,$file); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); $fileContent = curl_exec($ch); curl_close($ch); $zip->addFromString(basename($file), $fileContent); }else{ $zip->addFile($file,basename($file)); //向压缩包中添加文件 } } $zip->close(); //关闭压缩包] return $filename; }
有些接口还需要把压缩文件转为base64 便于传输
function ZipFileToBase64String($filename){ $base64 = null; $fileinfo = fopen($filename,"r"); if($fileinfo){ $filesize = filesize($filename); $content = fread($fileinfo,$filesize); $base64 = chunk_split(base64_encode($content)); } fclose($fileinfo); return $base64; }