1. 程式人生 > >PHP將多級目錄打包成zip檔案

PHP將多級目錄打包成zip檔案

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

bool (string $dirname ) bool ( 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  開頭的;的去掉。