怎么在PHP中生成一个zip压缩包

今天就跟大家聊聊有关怎么在PHP中生成一个zip压缩包,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

压缩一个文件

怎么在PHP中生成一个zip压缩包

我们将一个文件生成一个压缩包。

<?php
$path="c:/wamp/www/log.txt";
$filename="test.zip";
$zip=newZipArchive();
$zip->open($filename,ZipArchive::CREATE);//打开压缩包
$zip->addFile($path,basename($path));//向压缩包中添加文件
$zip->close();//关闭压缩包

上述代码将c:/wamp/www/log.txt文件压缩生成了test.zip,并保存在当前目录。

压缩多个文件

压缩多个文件,其实就是addFile执行多次,可以通过数组的遍历来实现。

<?php
$fileList=array(
"c:/wamp/www/log.txt",
"c:/wamp/www/weixin.class.php"
);
$filename="test.zip";
$zip=newZipArchive();
$zip->open($filename,ZipArchive::CREATE);//打开压缩包
foreach($fileListas$file){
$zip->addFile($file,basename($file));//向压缩包中添加文件
}
$zip->close();//关闭压缩包

压缩一个目录

<?php
functionaddFileToZip($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=newZipArchive();
if($zip->open('rsa.zip',ZipArchive::OVERWRITE)===TRUE){
addFileToZip('rsa/',$zip);//调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法
$zip->close();//关闭处理的zip文件
}

压缩并下载zip包

我的时候,我们需要打包之后,提供下载,然后删除压缩包。

可以分为以下几步:

  1. 判断给出的路径,是文件夹,还是文件。文件夹还需要遍历添加文件。

  2. 设置相关文件头,并使用readfile函数提供下载。

  3. 使用unlink函数删除压缩包

<?php
functionaddFileToZip($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=newZipArchive();
if($zip->open('rsa.zip',ZipArchive::OVERWRITE)===TRUE){
$path='rsa/';
if(is_dir($path)){//给出文件夹,打包文件夹
addFileToZip($path,$zip);
}elseif(is_array($path)){//以数组形式给出文件路径
foreach($pathas$file){
$zip->addFile($file);
}
}else{//只给出一个文件
$zip->addFile($path);
}
$zip->close();//关闭处理的zip文件
}

看完上述内容,你们对怎么在PHP中生成一个zip压缩包有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注恰卡编程网行业资讯频道,感谢大家的支持。

发布于 2021-04-15 01:55:16
收藏
分享
海报
0 条评论
164
上一篇:如何使用Python绘制热力图 下一篇:使用Nuxt.js怎么实现一个SSR前端博客
目录

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码