2010-09-30 165 views

回答

14

下面是一個例子:

<?php 

// Adding files to a .zip file, no zip file exists it creates a new ZIP file 

// increase script timeout value 
ini_set('max_execution_time', 5000); 

// create object 
$zip = new ZipArchive(); 

// open archive 
if ($zip->open('my-archive.zip', ZIPARCHIVE::CREATE) !== TRUE) { 
    die ("Could not open archive"); 
} 

// initialize an iterator 
// pass it the directory to be processed 
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("themes/")); 

// iterate over the directory 
// add each file found to the archive 
foreach ($iterator as $key=>$value) { 
    $zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key"); 
} 

// close and save archive 
$zip->close(); 
echo "Archive created successfully."; 
?> 
+1

偉大的代碼...我如何編輯這個ZIP壓縮嵌套的文件夾,排除所有的文件夾導致它?我所需的文件夾位於「/var/www/vhosts/mysite.com/dev/wp-content/themes/mytheme/」。當我運行這個腳本時,我得到一個var的開始文件夾然後www然後vhosts然後mysite.com等我缺少什麼? – 2013-04-11 15:51:44

+0

我是否理解,代碼也是通過「。」進行迭代的。和「..」目錄裏面的「主題/」?它看起來像這樣會導致問題,當您嘗試解壓縮存檔。 – Tamara 2015-06-12 16:52:14

+0

此代碼在解壓文件時會導致問題。 – 2015-10-21 17:22:45

3

當心阿德南的例子可能出現的問題:如果目標myarchive.zip是源文件夾中,那麼你需要排除的循環,或在創建存檔文件之前運行迭代器(如果它不存在)。這是一個修改後的腳本,它使用後一個選項,並將一些配置變量添加到頂部。不應該使用這個添加到現有的存檔。

<?php 
// Config Vars 

$sourcefolder = "./"   ; // Default: "./" 
$zipfilename = "myarchive.zip"; // Default: "myarchive.zip" 
$timeout  = 5000   ; // Default: 5000 

// instantate an iterator (before creating the zip archive, just 
// in case the zip file is created inside the source folder) 
// and traverse the directory to get the file list. 
$dirlist = new RecursiveDirectoryIterator($sourcefolder); 
$filelist = new RecursiveIteratorIterator($dirlist); 

// set script timeout value 
ini_set('max_execution_time', $timeout); 

// instantate object 
$zip = new ZipArchive(); 

// create and open the archive 
if ($zip->open("$zipfilename", ZipArchive::CREATE) !== TRUE) { 
    die ("Could not open archive"); 
} 

// add each file in the file list to the archive 
foreach ($filelist as $key=>$value) { 
    $zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key"); 
} 

// close the archive 
$zip->close(); 
echo "Archive ". $zipfilename . " created successfully."; 

// And provide download link ?> 
<a href="http:<?php echo $zipfilename;?>" target="_blank"> 
Download <?php echo $zipfilename?></a> 
+0

它不解壓縮。在解壓縮時顯示錯誤。 – 2015-10-21 17:25:33