ziparchive文件夹和文件排除当前文件夹

时间:2019-04-05 15:56:50

标签: php ziparchive

我有一个包含文件和子文件夹的文件夹:

base_folder_name
  -folder_01
    -file_01
    -file_02
  -folder_02
    -file_01
    ....etc

当我压缩文件夹时,我得到的正是这个结构。

但是我想从zip中排除主“ base_folder_name”文件夹,以便在提取文件时结构为:

-folder_01
    -file_01
    -file_02
  -folder_02
    -file_01
    ....etc

这是我的代码:

$rootPath = public_path() .'/storage/base_folder_name'; 
    //Initialize archive object
    $zip = new ZipArchive();
    $zip->open(public_path() .'/storage/base_folder_name/'base_folder_name.zip', ZipArchive::CREATE);
            $files = new \RecursiveIteratorIterator(
        new \RecursiveDirectoryIterator($rootPath),
        \RecursiveIteratorIterator::LEAVES_ONLY
    );

    foreach ($files as $name => $file)
    {
        // Skip directories (they would be added automatically)
        if (!$file->isDir()){
            // Get real and relative path for current file
            $filePath = $file->getRealPath();      
            $relativePath = substr($filePath, strlen($rootPath) + 1);
            log::info($relativePath);
            // Add current file to archive
            $zip->addFile($filePath, $relativePath);
        }
    }

0 个答案:

没有答案