咱們將一個文件生成一個壓縮包。php
<?php $path = "c:/wamp/www/log.txt"; $filename = "test.zip"; $zip = new ZipArchive(); $zip->open($filename,ZipArchive::CREATE); //打開壓縮包 $zip->addFile($path,basename($path)); //向壓縮包中添加文件 $zip->close(); //關閉壓縮包
上述代碼將c:/wamp/www/log.txt文件壓縮生成了test.zip,並保存在當前目錄。數組
壓縮多個文件,其實就是addFile執行屢次,能夠經過數組的遍從來實現函數
<?php $fileList = array( "c:/wamp/www/log.txt", "c:/wamp/www/weixin.class.php" ); $filename = "test.zip"; $zip = new ZipArchive(); $zip->open($filename,ZipArchive::CREATE); //打開壓縮包 foreach($fileList as $file){ $zip->addFile($file,basename($file)); //向壓縮包中添加文件 } $zip->close(); //關閉壓縮包
<?php function addFileToZip($path,$zip){ $handler=opendir($path); //打開當前文件夾由$path指定。 while(($filename=readdir($handler))!==false){ if($filename != "." && $filename != ".."){//文件夾文件名字爲'.'和‘..’,不要對他們進行操做 if(is_dir($path."/".$filename)){// 若是讀取的某個對象是文件夾,則遞歸 addFileToZip($path."/".$filename, $zip); }else{ //將文件加入zip對象 $zip->addFile($path."/".$filename); } } } @closedir($path); } $zip=new ZipArchive(); if($zip->open('rsa.zip', ZipArchive::OVERWRITE)=== TRUE){ addFileToZip('rsa/', $zip); //調用方法,對要打包的根目錄進行操做,並將ZipArchive的對象傳遞給方法 $zip->close(); //關閉處理的zip文件 }
個人時候,咱們須要打包以後,提供下載,而後刪除壓縮包。spa
能夠分爲如下幾步:code
readfile
函數提供下載。unlink
函數刪除壓縮包
<?php function addFileToZip($path,$zip){ $handler=opendir($path); //打開當前文件夾由$path指定。 while(($filename=readdir($handler))!==false){ if($filename != "." && $filename != ".."){//文件夾文件名字爲'.'和‘..’,不要對他們進行操做 if(is_dir($path."/".$filename)){// 若是讀取的某個對象是文件夾,則遞歸 addFileToZip($path."/".$filename, $zip); }else{ //將文件加入zip對象 $zip->addFile($path."/".$filename); } } } @closedir($path); } $zip=new ZipArchive(); if($zip->open('rsa.zip', ZipArchive::OVERWRITE)=== TRUE){ $path = 'rsa/'; if(is_dir($path)){ //給出文件夾,打包文件夾 addFileToZip($path, $zip); }else if(is_array($path)){ //以數組形式給出文件路徑 foreach($path as $file){ $zip->addFile($file); } }else{ //只給出一個文件 $zip->addFile($path); } $zip->close(); //關閉處理的zip文件 }