php如何压缩空文件夹,如何使用PHP压缩整个文件夹

小编典典

代码已于2015/04/22更新。

压缩整个文件夹:

// 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();

压缩整个文件夹+删除除“ important.txt”以外的所有文件:

// 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);

// Initialize empty "delete list"

$filesToDelete = array();

// 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);

// Add current file to "delete list"

// delete it later cause ZipArchive create archive only after calling close function and ZipArchive lock files until archive created)

if ($file->getFilename() != 'important.txt')

{

$filesToDelete[] = $filePath;

}

}

}

// Zip archive will be created only after closing object

$zip->close();

// Delete all files from "delete list"

foreach ($filesToDelete as $file)

{

unlink($file);

}

2020-05-26

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值