php使用ZipArchive函数实现文件的压缩与解压缩
作者:nian860314 时间:2023-07-12 20:58:19
PHP ZipArchive 是PHP自带的扩展类,可以轻松实现ZIP文件的压缩和解压,使用前首先要确保PHP ZIP 扩展已经开启,具体开启方法这里就不说了,不同的平台开启PHP扩增的方法网上都有,如有疑问欢迎交流。这里整理一下利用php zipArchive进行文件的压缩与解压缩的常用的示例供参考。
一、解压缩zip文件
$zip=new ZipArchive;//新建一个ZipArchive的对象
if($zip->open('test.zip')===TRUE){
$zip->extractTo('images');//假设解压缩到在当前路径下images文件夹内
$zip->close();//关闭处理的zip文件
}
二、将文件压缩成zip文件
$zip=new ZipArchive;
if($zip->open('test.zip',ZipArchive::OVERWRITE)===TRUE){
$zip->addFile('image.txt');//假设加入的文件名是image.txt,在当前路径下
$zip->close();
}
三、文件追加内容添加到zip文件
$zip=new ZipArchive;
$res=$zip->open('test.zip',ZipArchive::CREATE);
if($res===TRUE){
$zip->addFromString('test.txt','file content goes here');
$zip->close();
echo 'ok';
}else{
echo 'failed';
}
四、将文件夹打包成zip文件
function addFileToZip($path,$zip){
$handler=opendir($path); //打开当前文件夹由$path指定。
while(($filename=readdir($handler))!==false){
if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..',不要对他们进行操作
if(is_dir($path."/".$filename)){// 如果读取的某个对象是文件夹,则递归
addFileToZip($path."/".$filename, $zip);
}else{ //将文件加入zip对象
$zip->addFile($path."/".$filename);
}
}
}
@closedir($path);
}
$zip=new ZipArchive();
if($zip->open('images.zip', ZipArchive::OVERWRITE)=== TRUE){
addFileToZip('images/', $zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法
$zip->close(); //关闭处理的zip文件
}
标签:php,ziparchive,压缩
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
pytorch 使用单个GPU与多个GPU进行训练与测试的方法
2022-04-04 10:39:07
Mysql误操作后利用binlog2sql快速回滚的方法详解
2024-01-23 19:00:31
python GUI库图形界面开发之PyQt5动态(可拖动控件大小)布局控件QSplitter详细使用方法与实例
2023-06-20 22:10:04
![](https://img.aspxhome.com/file/2023/3/66373_0s.png)
MySQL 数据库优化的具体方法说明
2024-01-15 08:26:13
解决Shell执行python文件,传参空格引起的问题
2021-08-22 10:05:25
python交互模式下输入换行/输入多行命令的方法
2022-06-08 07:18:37
Django-migrate报错问题解决方案
2021-11-05 13:30:16
使用Djongo模块在Django中使用MongoDB数据库
2024-01-21 21:10:17
![](https://img.aspxhome.com/file/2023/1/79481_0s.jpg)
Web前端应用十种常用技术
2010-09-01 20:46:00
![](https://img.aspxhome.com/file/UploadPic/20109/1/01-96s.jpg)
Mysql CAST函数的具体使用
2024-01-16 16:17:04
![](https://img.aspxhome.com/file/2023/5/99495_0s.png)
asp form 表单验证函数
2011-04-04 11:10:00
SQL Server开发智能提示插件SQL Prompt介绍
2024-01-23 01:02:54
![](https://img.aspxhome.com/file/2023/9/99979_0s.jpg)
爱你就要说出来,来表白吧
2008-11-23 16:23:00
![](https://img.aspxhome.com/file/UploadPic/200811/23/loveyou-38s.gif)
Oracle删除字段中的空格、回车及指定字符的实例代码
2024-01-18 18:10:07
利用Python将时间或时间间隔转为ISO 8601格式方法示例
2022-12-06 22:18:25
![](https://img.aspxhome.com/file/2023/5/115005_0s.png)
Safari参考样式库之webkit
2009-07-26 09:50:00
![](https://img.aspxhome.com/file/UploadPic/20097/26/webkit1-13s.jpg)
keras处理欠拟合和过拟合的实例讲解
2022-06-23 05:14:38
![](https://img.aspxhome.com/file/2023/8/104948_0s.jpg)
Keras之fit_generator与train_on_batch用法
2021-07-10 18:19:31
MySQL中的全表扫描和索引树扫描 的实例详解
2024-01-24 02:39:43
![](https://img.aspxhome.com/file/2023/5/126255_0s.png)
NLTK的安装教程及安装错误解决方案
2022-09-24 04:59:33
![](https://img.aspxhome.com/file/2023/2/68282_0s.png)