我们将一个文件生成一个压缩包<?php
$fileList = array(
"c:/wamp/www/log.txt",
"c:/wamp/www/weixin.class.php"
);
$filename = "test.zip";
$zip = new ZipArchive();
$zip->open($filename,ZipArchive::CREATE); //打开压缩包
foreach($fileList as $file){
$zip->addFile($file,basename($file)); //向压缩包中添加文件
}
$zip->close(); //关闭压缩包
ZipArchive::open第二个参数说明:
ZipArchive::OVERWRITE
总是以一个新的压缩包开始,此模式下如果已经存在则会被覆盖。
ZipArchive::CREATE
如果不存在则创建一个zip压缩包。
ZipArchive::EXCL
如果压缩包已经存在,则出错。
ZipArchive::CHECKCONS
对压缩包执行额外的一致性检查,如果失败则显示错误。
压缩单个文件new ZipArchive();
$flag = $zip->open('C:/out.zip', ZipArchive::OVERWRITE);
if($flag!==true){
echo "open error code: {$flag}\n";
exit();
}
$zip->addFile('C:/1.txt', '1.txt'); //zip文件中的文件名为1.txt,如果忽略,则会多一个名为C:的文件夹
$flag = $zip->close();
echo $flag?'success':'fail';
压缩多个文件
$zip = new ZipArchive();
$flag = $zip->open('C:/out.zip', ZipArchive::OVERWRITE);
if($flag!==true){
echo "open error code: {$flag}\n";
exit();
}
$zip->addFile('C:/1.txt', '1.txt');
$zip->addFile('C:/2.txt', '2.txt');
$flag = $zip->close();
echo $flag?'success':'fail';
添加文件到压缩包
如果存在压缩包,则添加;若不存在,则新建$zip = new ZipArchive();
$flag = $zip->open('C:/out.zip', ZipArchive::CREATE);
if($flag!==true){
echo "open error code: {$flag}\n";
exit();
}
$zip->addFile('C:/2.txt', 'folder/2.txt');
$flag = $zip->close();
echo $flag?'success':'fail';
压缩文件夹
/**
* @param string $basePath 带/结尾
* @param string $relativePath 不带/开头
* @param ZipArchive $zip
*/
function zipFolder($basePath, $relativePath, ZipArchive $zip)
{
$handler = opendir($basePath.$relativePath); //打开当前文件夹
while(($filename = readdir($handler))!==false){
if($filename!='.' && $filename!='..'){
if(is_dir($basePath.$relativePath.'/'.$filename))
zipFolder($basePath, $relativePath.'/'.$filename, $zip);
else
$zip->addFile($basePath.$relativePath.'/'.$filename, $relativePath.'/'.$filename);
}
}
closedir($handler);
}
$zip = new ZipArchive();
$flag = $zip->open('C:/out.zip', ZipArchive::OVERWRITE);
if($flag!==true){
echo "open error code: {$flag}\n";
exit();
}
zipFolder('C:/', 'test', $zip); //压缩文件夹C:/test,并且压缩包以test文件夹开始
$flag = $zip->close();
echo $flag?'success':'fail';