下面的代码成功地创建了一个指定目录和所有子目录的zip文件。我遇到的问题是,最终的结果是删除根目录下每个文件名和文件夹名的第一个字符,而在子目录中没有出现同样的行为。
<?php
require('../config/config.php');
$rootPath = $abs_path.'/includes/qrcodes/'; // SOURCE FOLDER TO ZIP
$zipFilename = 'qr_images.zip';
$zip = new ZipArchive();
$zip->open($zipFilename, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($files as $name => $file)
{
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
if (!$file->isDir())
{
$zip->addFile($filePath, $relativePath);
}else {
if($relativePath !== false)
$zip->addEmptyDir($relativePath);
}
}
$zip->close();
?>
目前,产生的 zip 文件包括
文件夹应该命名为 "radios"、"infosys "和 "vears"。
这段代码似乎是为$rootpath变量设计的,没有尾部的反斜杠。如果你想改变它 $rootPath = $abs_path.'/includes/qrcodes';
在substr处的+1是必须的,否则相对路径将以''开头。否则相对路径将以''开头。