// 要压缩的文件夹
$dir=getBasePath().'/storage/AgentQrCode/201908206320/';
// 保存的压缩文件
$compress_path=$dir.'file.zip';
$rootPath = realpath($dir);
// Initialize archive object
$zip = new \ZipArchive();
$zip->open($compress_path, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($rootPath),
\RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// 我们要跳过所有子目录
if (!$file->isDir())
{
// 用 substr/strlen 获取文件扩展名
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
![13034051-1a007ca0a9f705b4.png](https://i-blog.csdnimg.cn/blog_migrate/4c79bfe8a0e6be76e7f47ecdea27f154.webp?x-image-process=image/format,png)
image.png