使用PHP压缩整个文件夹排除一些子目录

时间:2018-03-23 06:10:07

标签: php zip

如何使用PHP压缩整个文件夹?

// Get real path for our folder
$rootPath = realpath('folder-to-zip');

// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$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);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();

我已经尝试过这个并且效果很好,但是我需要排除一些子目录,我该怎么做?

该代码将压缩目录中的所有文件, 示例:

Main Folder
 -folder A
 -folder B
 -folder C
  -upload
   -data a
   -data b
   -data c

我想压缩所有这些,但排除“数据b”和“数据c”

我改变了这样的foreach,但它仍然压缩了所有文件

foreach ($files as $name => $file){
        if (!$file->isDir()){
            $filePath = $file->getRealPath();
            $relativePath = substr($filePath, strlen($rootPath) + 1);
            $get_id_directory = strpos($relativePath,$view_id_noSpace);
            $get_upload_directory = strpos($relativePath,'upload');
            $zip->addFile($filePath, $relativePath);

            if($get_upload_directory != ''){
                if($get_id_directory == ''){
                    //$zip->addFile($filePath, $relativePath);
                    $zip->deleteName($filePath, $relativePath);
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:-1)

实际命令是:

zip -r myarchive.zip dir1 -x dir1/ignoreDir1/**\* dir1/ignoreDir2/**\*

这里myarchive.zip是要创建的zip文件的名称。 dir1是要压缩的文件夹。 ignoreDir1,ignoreDir2是您不想包含在zip文件夹中的文件夹。