解决php ZipArchive压缩zip文件多级目录

zip

解决的方法就是添加文件后加个 [路径]文件名

ZipArchive :: addFromString

(PHP 5> = 5.2.0,PHP 7,PECL zip> = 1.1.0)

ZipArchive :: addFromString - 使用其内容将文件添加到ZIP存档

说明

bool ZipArchive::addFromString ( string $localname , string $contents )

参数

  • localname

    要创建的条目的名称。

  • contents

    用于创建条目的内容。它用于二进制安全模式。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
$zip->addFile ($dir.'images1.jpg');

$zip->addFile ($dir.'test.zip','images1.jpg');//一级
/*压缩后的效果如
* test.zip
* images1.zip
*/
$zip->addFile ($dir.'test.zip','images/images1.jpg');//二级
/*压缩后的效果如
* test.zip
* imgages //目录
* images1.zip
*/

ZipArchive类是系统自带的,很实用。

PHP手册:http://php.net/manual/zh/class.ziparchive.php

ZipArchive类

函数 功能
open 打开一个zip文件
close 关闭zip文件(文件是打开的或新建的)
addEmptyDir 添加一个新的目录
addFile 添加一个文件
addFromString 使用文件内容添加文件
addGlob 使用glob模式添加文件
addPattern 使用PCRE模式添加文件
deleteIndex 使用索引删除一个文件或目录
deleteName 使用名称删除一个文件或目录
extractTo 解压Zip文件
getArchiveComment 返回Zip文件的说明
getCommentIndex 使用索引返回一个文件或目录的说明
getCommentName 使用名称返回一个文件或目录的说明
getExternalAttributesIndex 使用索引检索一个文件或目录的外部属性
getExternalAttributesName 使用名称检索一个文件或目录的外部属性
getFromIndex 使用索引返回文件的内容
getFromName 使用文件名称返回文件的内容
getNameIndex 使用索引返回一个文件或目录的名称
getStatusString 返回错误状态消息
getStream 得到一个文件处理程序中的文件或目录名称(只读)。
locateName 返回文件或目录的索引
renameIndex 通过索引重命名一个文件或目录
renameName 通过文件名重命名一个文件或目录
setArchiveComment 设置ZIP归档的说明
setCommentIndex 通过索引设置一个文件或目录的说明
setCommentName 通过文件名设置一个文件或目录的说明
setCompressionIndex 通过索引设置一个文件或目录的压缩方法
setCompressionName 通过文件名设置一个文件或目录的压缩方法
setEncryptionIndex 通过索引设置一个文件或目录的加密方法
setEncryptionName 通过文件名设置一个文件或目录的加密方法
setExternalAttributesIndex 通过索引设置一个条目的外部属性
setExternalAttributesName 通过文件名设置一个条目的外部属性
setPassword 为ZIP文件设置密码(解压时候用)
statIndex 通过索引得到一个文件或目录的详细信息
statName 通过文件名得到一个文件或目录的详细信息
unchangeAll 撤销所有更改
unchangeArchive 恢复所有更改
unchangeIndex 通过索引恢复一个文件或目录的所有更改
unchangeName 通过文件名恢复一个文件或目录的所有更改

ZipArchive类的公有属性:

属性 说明
status ZipArchive 的状态
statusSys ZipArchive 的系统状态
numFiles 压缩包里的文件数
filename 在文件系统里的文件名
comment 压缩包的说明