PHP ZipArchive 删除文件名的第一个字符。

问题描述 投票:0回答:1

下面的代码成功地创建了一个指定目录和所有子目录的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
  • 文件夹
    • infosys_1.png
  • 车辆
    • 车辆_1.png
    • 车辆_2.png

文件夹应该命名为 "radios"、"infosys "和 "vears"。

php ziparchive php-zip-archive
1个回答
0
投票

这段代码似乎是为$rootpath变量设计的,没有尾部的反斜杠。如果你想改变它 $rootPath = $abs_path.'/includes/qrcodes'; 在substr处的+1是必须的,否则相对路径将以''开头。否则相对路径将以''开头。

© www.soinside.com 2019 - 2024. All rights reserved.