使用 ZipArchive 打包文件或文件夹,采用最后一层文件夹目录作为打包文件的根目录:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php


namespace App\Service;


class ZipService
{

public $zipObj;

public function __construct()
{
$this->zipObj = new \ZipArchive();

}

/**
* zip 文件夹打包
* @param $filePath | 打包的文件路径
* @param $zipFileName | 生成的zip文件路径
* @return array|bool
*/
public function createZip($filePath, $zipFileName)
{
$zip = $this->zipObj;
if (!$zip->open($zipFileName, $zip::CREATE)) {
$msg = "创建" . $zipFileName . "失败";
return ['ok' => false, 'msg' => $msg];
}

//以最后的文件夹作为打包文件的根路径
$dirArr = explode(DIRECTORY_SEPARATOR, $filePath);
$zipFilePath = $dirArr[count($dirArr) - 1] . DIRECTORY_SEPARATOR;
$this->addFileToZip($filePath, $zip, $zipFilePath);

$zip->close();
return true;
}

/**
* zip 文件添加操作
* @param $filePath | 打包的文件路径
* @param $zip | ZipArchive对象
* @param $zipRootPath | zip文件的根目录路径
*/
function addFileToZip($filePath, $zip, $zipRootPath)
{
$handler = opendir($filePath);
/**
* 其中 $filename = readdir($handler) 是每次循环的时候将读取的文件名赋值给 $filename,为了不陷于死循环,所以还要让 $filename !== false
*/
while (($filename = readdir($handler)) !== false) {
if ($filename != "." && $filename != "..") {
// 对于文件夹,is_dir会返回TRUE,注意路径是 $newPath
$newPath = $filePath . DIRECTORY_SEPARATOR . $filename;
if (is_dir($newPath)) {
$nowPath = $zipRootPath . $filename . DIRECTORY_SEPARATOR;
$this->addFileToZip($newPath, $zip, $nowPath);
} else {
//文件加入zip对象
$zip->addFile($newPath, $zipRootPath . $filename);
}
}
}

closedir($handler);
}

}

附:相关 php composer 包:chumper/zipper

原文链接

https://learnku.com/articles/58662