【发布时间】:2020-05-22 14:28:38
【问题描述】:
下面的代码成功创建了一个指定目录和所有子目录的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 文件包括:
- adios(文件夹)
- radio_1.png
- radio_2.png
- nfosys(文件夹)
- infosys_1.png
- ehicles(文件夹)
- vehicle_1.png
- vehicle_2.png
文件夹应命名为“radios”、“infosys”和“vehicles”。
【问题讨论】:
-
因为
+ 1在substr()调用中。 -
@Barmar 谢谢你,我觉得很愚蠢。当您借用您不完全理解的代码时,就会发生这种情况。我删除了 +1 并解决了问题。有什么理由让它在哪里/过去是有意义的吗?
-
您复制的代码可能在
$root_path的末尾没有/,因此它添加了1 以跳过作为分隔符添加到完整路径中的/。
标签: php ziparchive php-zip-archive