PHP將多級目錄打包成zip文件


最近接觸PHP,需要用到zip壓縮,在網上搜索的一大堆,發現代碼都不低於50行。  而且調用還很費事(基礎太少看不懂)。讓我收獲的是Php提供有一個ZipArchive類,並有如下方法。

 

bool addEmptyDir(string $dirname )
bool addFilestring $filename [, string$localnameNULL[, int$start = 0 [, int $length = 0 ]]] )

mixed open(string $filename [, int$flags] )  

 

bool close(void )

回憶用java中寫的思路,便摩擦php,實現如下:

|--調用

 

[php]  view plain  copy
 
 print?
  1. //創建<span style="font-family: Arial, Helvetica, sans-serif;">ZipArchive對象</span>  
  2. $zip = new ZipArchive();  
  3. //參數1:zip保存路徑,參數2:ZIPARCHIVE::CREATE沒有即是創建  
  4. if(!$zip->open("$exportPath.zip",ZIPARCHIVE::CREATE))  
  5. {  
  6.     echo "創建[$exportPath.zip]失敗<br/>";return;  
  7. }  
  8. //echo "創建[$exportPath.zip]成功<br/>";  
  9. $this->createZip(opendir($exportPath),$zip,$exportPath);  
  10. $zip->close();  

 

|--執行

 

[php]  view plain  copy
 
 print?
  1. /*壓縮多級目錄 
  2.     $openFile:目錄句柄 
  3.     $zipObj:Zip對象 
  4.     $sourceAbso:源文件夾路徑 
  5. */  
  6. function createZip($openFile,$zipObj,$sourceAbso,$newRelat = '')  
  7. {  
  8.     while(($file = readdir($openFile)) != false)  
  9.     {  
  10.         if($file=="." || $file=="..")  
  11.             continue;  
  12.           
  13.         /*源目錄路徑(絕對路徑)*/  
  14.         $sourceTemp = $sourceAbso.'/'.$file;  
  15.         /*目標目錄路徑(相對路徑)*/  
  16.         $newTemp = $newRelat==''?$file:$newRelat.'/'.$file;  
  17.         if(is_dir($sourceTemp))  
  18.         {  
  19.             //echo '創建'.$newTemp.'文件夾<br/>';  
  20.             $zipObj->addEmptyDir($newTemp);/*這里注意:php只需傳遞一個文件夾名稱路徑即可*/  
  21.             $this->createZip(opendir($sourceTemp),$zipObj,$sourceTemp,$newTemp);  
  22.         }  
  23.         if(is_file($sourceTemp))  
  24.         {  
  25.             //echo '創建'.$newTemp.'文件<br/>';  
  26.             $zipObj->addFile($sourceTemp,$newTemp);  
  27.         }  
  28.     }  
  29. }  

 

|--補充

 開啟PHP支持ZipArchive
在php.ini文件中將extension=php_zip.dll  開頭的;的去掉。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM