2010-09-30 160 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