ziparchive扩展使用类

本文介绍了一个使用 PHP 的 ZipArchive 类进行文件压缩和解压缩的实际应用案例。该示例展示了如何创建、读取、修改 ZIP 文件,包括批量添加符合特定条件的文件到 ZIP 包、获取 ZIP 文件内的文件列表及根据文件名定位文件等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?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);		
	}

}


### PHP 中 ZipArchive 扩展的用法 #### 安装与配置 为了使用 `ZipArchive` ,在大多数情况下需要确保已安装并启用了相应的 PHP 扩展。对于 Linux 用户而言,可以通过包管理器来完成这项工作;而对于 Windows 用户,则需确认 php.ini 文件里有正确的设置[^1]。 - **Linux (Debian/Ubuntu)**: ```bash sudo apt-get install php-zip ``` - **Windows**: 编辑 `php.ini` 文件取消注释如下行: ```ini extension=php_zip.dll ``` 重启 Web 服务器使更改生效。 #### 创建 ZIP 归档 一旦环境准备就绪,就可以利用 `ZipArchive::create()` 方法或者构造函数实例化一个新的 `ZipArchive` 对象,并通过调用成员函数如 `addFile()` 或者 `addFromString()` 来向其中添加文件或字符串内容[^2]。 ```php <?php $zip = new \ZipArchive(); if ($zip->open('test.zip', \ZipArchive::CREATE) === TRUE) { $zip->addFile('/path/to/index.php', 'newname.php'); $zip->close(); } else { echo 'Failed to create archive'; } ?> ``` 上述代码展示了怎样创建名为 test.zip 的新存档并将指定路径下的 index.php 添加进去同时重命名为 newname.php。 #### 解压 ZIP 文件 解压缩操作同样简单明了,只需打开现有的 .zip 文件并通过 `extractTo()` 函数指定期望的目标目录即可。 ```php <?php $zip = new \ZipArchive; $res = $zip->open('game.zip'); if ($res === TRUE) { $zip->extractTo('/my/game/dir/'); $zip->close(); echo 'ok'; } else { echo 'failed, code:' . $res; } ?> ``` 这段脚本会尝试打开 game.zip 并将其全部内容提取到 /my/game/dir/ 下面去。 #### 访问 ZIP 内部结构而不必先解压 除了基本的打包和拆包功能外,还可以借助于 `getFromName()` 和其他似的 API 获取特定项的内容而无需实际展开整个档案[^3]。 ```php <?php $zip = new \ZipArchive; if ($zip->open('game.zip') === TRUE) { $content = $zip->getFromName('readme.txt'); var_dump($content); $zip->close(); } else { echo '无法打开ZIP文件'; } ?> ``` 此片段演示了如何直接读取 readme.txt 的文本内容而不是把它单独拿出来保存成物理文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值