最近接觸PHP,需要用到zip壓縮,在網上搜索的一大堆,發現代碼都不低於50行。 而且調用還很費事(基礎太少看不懂)。讓我收獲的是Php提供有一個ZipArchive類,並有如下方法。
bool addEmptyDir(string
$dirname )
bool addFile( string
$filename [, string$localname= NULL[, int$start = 0 [, int $length = 0 ]]] )
mixed open(string $filename [, int$flags] )
bool close(void )
回憶用java中寫的思路,便摩擦php,實現如下:
|--調用
- //創建<span style="font-family: Arial, Helvetica, sans-serif;">ZipArchive對象</span>
- $zip = new ZipArchive();
- //參數1:zip保存路徑,參數2:ZIPARCHIVE::CREATE沒有即是創建
- if(!$zip->open("$exportPath.zip",ZIPARCHIVE::CREATE))
- {
- echo "創建[$exportPath.zip]失敗<br/>";return;
- }
- //echo "創建[$exportPath.zip]成功<br/>";
- $this->createZip(opendir($exportPath),$zip,$exportPath);
- $zip->close();
|--執行
- /*壓縮多級目錄
- $openFile:目錄句柄
- $zipObj:Zip對象
- $sourceAbso:源文件夾路徑
- */
- function createZip($openFile,$zipObj,$sourceAbso,$newRelat = '')
- {
- while(($file = readdir($openFile)) != false)
- {
- if($file=="." || $file=="..")
- continue;
- /*源目錄路徑(絕對路徑)*/
- $sourceTemp = $sourceAbso.'/'.$file;
- /*目標目錄路徑(相對路徑)*/
- $newTemp = $newRelat==''?$file:$newRelat.'/'.$file;
- if(is_dir($sourceTemp))
- {
- //echo '創建'.$newTemp.'文件夾<br/>';
- $zipObj->addEmptyDir($newTemp);/*這里注意:php只需傳遞一個文件夾名稱路徑即可*/
- $this->createZip(opendir($sourceTemp),$zipObj,$sourceTemp,$newTemp);
- }
- if(is_file($sourceTemp))
- {
- //echo '創建'.$newTemp.'文件<br/>';
- $zipObj->addFile($sourceTemp,$newTemp);
- }
- }
- }
|--補充
開啟PHP支持ZipArchive
在php.ini文件中將extension=php_zip.dll 開頭的;的去掉。
