在php_zip扩展中提供了两种对zip压缩包的处理方式,一种是ZipArchive类,一种是Zip函数,相对于zip函数而言ZipArchive类对zip压缩和解压处理的更加完善,现在我们就对ZipArchive中的常用方法做一个简单的介绍
ZipArchive常用函数
-
1
打开压缩包函数,关闭资源函数
mixed ZipArchive::open ( string $filename [, int $flags ] )
$flag 参数如果在解压的情况下可以不用填写,如果是压缩的情况下可使用ZipArchive::CREATE,ZipArchive::OVERWRITE,ZipArchive::EXCL,ZipArchive::CHECKCONS创建一个zip
如果打开成功则返回true,失败的情况下返回错误码
bool ZipArchive::close ( void )
-
2
根据索引获取条目名称(包含全路径)
string ZipArchive::getNameIndex ( int $index [, int $flags ] )
int ZipArchive::locateName ( string $name [, int $flags ] ) 根据文件名返回名称所在压缩包中的索引位置
-
3
向压缩包中添加一个文件
bool ZipArchive::addFile ( string $filename [, string $localname = NULL [, int $start = 0 [, int $length = 0 ]]] )
$localname如果提供的话 ,如果文件在zip中已经存在,该文件将会本新的文件覆盖
-
4
添加内容到zip中并指定在zip的文件名称
bool ZipArchive::addFromString ( string $localname , string $contents )
-
5
将文件批量加入到zip压缩包中的方法
bool ZipArchive::addPattern ( string $pattern [, string $path = "." [, array $options = array() ]] )
$pattern 正则表达式
$path 文件路徑,将被扫描的目录。默认为当前工作目录。
$options 可填写的选项有add_path,remove_path,remove_all_path
addPattern是通过扫描$path指定的文件夹下满足正则的文件添加到add_path指定的文件夹下,移除zip中remove_path指定的文件夹或者remove_all_path全部文件
-
6
zip提供了一种快速解压的方式叫提取
bool ZipArchive::extractTo ( string $destination [, mixed $entries ] )
$destination 指定提取后的地址
$entries 如果设置,那么内容必须是zip中的问文件,表示提供这些文件
$zip = new ZipArchive();
$res = $zip->open('Study.zip');
if($res == true){
var_dump($zip->extractTo("hello/"));
$zip->close();
}else{
echo 'failed code '.$res;
}
-
7
zip中文件重命名
bool ZipArchive::setCompressionIndex ( int $index , int $comp_method [, int $comp_flags = 0 ] )
bool ZipArchive::setCompressionName ( string $name , int $comp_method [, int $comp_flags = 0 ] )
$index 索引项在zip中的索引
$name 索引项在zip中的名称
END
获取zip压缩包中内容列表的实例
-
1
$zip = new ZipArchive();
$res = $zip->open('demo.zip');
if($res == true){
for ($i=0; $i < $zip->numFiles ; $i++) {
echo $zip->getNameIndex($i),"<br/>";
}
}
$zip->close();
END
ZipArchive版,使用zipArchive解压十分简单
-
1
$zip = new ZipArchive();
$res = $zip->open('demo.zip');
if($res == true){
$zip->extractTo('demo'); 解压到当前目录的demo文件夹下(demo没有会自动创建)
}
$zip->close();
END
压缩(php_zip只有zipArchive提供了压缩功能)
-
1
$zip = new ZipArchive();
$res = $zip->open('f.zip',ZipArchive::CREATE);
if($res == true){
makeZip($zip,"E:/www/com_all/",".");
$zip->close();
}
function makeZip($zip,$src_dir,$desc_dir){递归处理文件夹下的文件
$dir = $desc_dir;
$src = realpath($src_dir);
if(is_dir($src)){
if($dh = opendir($src)){
while (($file = readdir($dh)) !== false) {
if($file != "." && $file != ".."){
$type = filetype($src ."/". $file);
switch ($type) {
case 'dir':
makeZip($zip,$src."/".$file,$dir."/".$file);
break;
default:
$zip->addFile($src."/".$file,$dir."/".$file);
break;
}
unset($type);
}
}
closedir($dh);
}
}
unset($dir);
unset($src);
}
END
文章评论