// 要压缩的文件夹
$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();
image.png
网友评论