<?php
$src_dir = "D:".DIRECTORY_SEPARATOR."wwwroot".DIRECTORY_SEPARATOR."tmanage".DIRECTORY_SEPARATOR."pc";
$des_dir =".";
$zip = new Zipdemo("f.zip");
//echo $zip->unzip("ss");
//print_r($zip->zipdetail());
$options = ['add_path'=>'/helloworld/','remove_all_path'=True];
var_dump($zip->addZipGroup('/\.(?:php|txt)$/',"D:".DIRECTORY_SEPARATOR."wwwroot".DIRECTORY_SEPARATOR."tmanage".DIRECTORY_SEPARATOR."nbproject",$options));
echo $zip->fileIndexByName("./components/account/Account.php");
Class Zipdemo{
public $zipobj;
public $res;
function __construct($zipname){
$this->zipobj = new ZipArchive();
$this->res = $this->zipobj->open('f.zip',ZipArchive::CREATE);
}
//生成zip
public function createZip($src_path,$desc_path){
if($this->res == true){
$this->makeZip($src_path,$desc_path);
return true;
}
}
//解压缩
public function unzip($desc_path){
$desc_path = realpath($desc_path);
$type = filetype($desc_path);
if('dir'!=$type){
return false;
}
if($this->res==true){
return $this->zipobj->extractTo($desc_path);
}
}
//zip内容列表
public function zipdetail(){
$detail=[];
if($this->res==true){
for ($i=0; $i < $this->zipobj->numFiles ; $i++) {
$detail[]=$this->zipobj->getNameIndex($i);
}
}
return $detail;
}
//根据文件名返回在zip中的索引
public function fileIndexByName($filename){
return $this->zipobj->locateName ($filename);
}
//添加内容到zip中指定文件
public function addStringToFile($filename,$string){
return $this->zipobj->addFromString($filename,$string);
}
//批量添加到zip
/**
$pattern 正则表达式
$path 文件路徑,将被扫描的目录。默认为当前工作目录。
$options 可填写的选项有add_path,remove_path,remove_all_path
addPattern是通过扫描$path指定的文件夹下满足正则的文件添加到add_path指定的文件夹下,移除zip中remove_path指定的文件夹或者remove_all_path全部文件
*/
public function addZipGroup($pattern,$path,$options){
return $this->zipobj->addPattern($pattern,$path,$options);
}
function __destruct(){
$this->zipobj->close();
}
//执行生成zip
private function makeZip($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.DIRECTORY_SEPARATOR.$file);
switch ($type) {
case 'dir':
$this->makeZip($src.DIRECTORY_SEPARATOR.$file,$dir.DIRECTORY_SEPARATOR.$file);
break;
default:
$this->zipobj->addFile($src.DIRECTORY_SEPARATOR.$file,$dir.DIRECTORY_SEPARATOR.$file);
break;
}
unset($type);
}
}
closedir($dh);
}
}else{
$this->zipobj->addFile($src.DIRECTORY_SEPARATOR.$file,$dir.DIRECTORY_SEPARATOR.$file);
}
unset($dir);
unset($src);
}
}
ziparchive扩展使用类
最新推荐文章于 2023-07-20 08:31:00 发布