php使用ZipArchive把已文件夹压缩
时间: 2024-12-02 11:15:56 浏览: 16
在PHP中,你可以使用`ZipArchive`类来创建、读取和管理ZIP压缩文件,包括将目录内容压缩到一个ZIP档案中。以下是一个基本的例子,展示了如何使用`ZipArchive`操作文件夹:
```php
<?php
// 创建 ZipArchive 对象
$zip = new ZipArchive();
// 检查能否打开文件,如果能则删除已存在的文件,防止覆盖
if ($zip->open('archive.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
echo "Failed to open or create zip file.";
} else {
// 遍历需要压缩的文件夹
$dirPath = 'path_to_your_directory'; // 替换为实际路径
if (is_dir($dirPath)) {
$files = scandir($dirPath);
// 排除 . 和 .. 文件夹
array_shift($files); // 删除 . 目录
array_shift($files); // 删除 .. 目录
foreach ($files as $file) {
// 获取相对路径,如果是目录,则递归处理
$relativePath = rtrim($dirPath . '/' . $file, '\\/');
if (is_file($dirPath . '/' . $file)) {
// 添加文件到ZIP
$zip->addFile($dirPath . '/' . $file, $relativePath);
} elseif (is_dir($dirPath . '/' . $file)) {
// 如果是目录,添加空目录
$zip->addEmptyDir($relativePath);
}
}
}
// 关闭ZipArchive
$zip->close();
echo "Compression successful!";
}
阅读全文
相关推荐















