【问题标题】:PHP ZipArchive Removing First Character of FilenamesPHP ZipArchive 删除文件名的第一个字符
【发布时间】: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”。

【问题讨论】:

  • 因为+ 1substr() 调用中。
  • @Barmar 谢谢你,我觉得很愚蠢。当您借用您不完全理解的代码时,就会发生这种情况。我删除了 +1 并解决了问题。有什么理由让它在哪里/过去是有意义的吗?
  • 您复制的代码可能在$root_path 的末尾没有/,因此它添加了1 以跳过作为分隔符添加到完整路径中的/

标签: php ziparchive php-zip-archive


【解决方案1】:

该代码似乎是为 $rootpath 变量设计的,没有尾部反斜杠。如果您要更改它$rootPath = $abs_path.'/includes/qrcodes';,则需要 substr 处的 +1。否则,相对路径将以“/”开头。

【讨论】:

    猜你喜欢
    • 2020-11-17
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2018-11-09
    • 1970-01-01
    • 2018-12-03
    • 2011-06-24
    相关资源
    最近更新 更多