问题:
如何使用 PHP 创建整个文件夹的 ZIP 存档PHP?另外,如何在压缩后删除文件夹中的所有内容(不包括特定文件)?
答案:
1.压缩整个文件夹:
$rootPath = rtrim($rootPath, '\/'); $rootPath = realpath('folder-to-zip'); $zip = new ZipArchive(); $zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE); $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($files as $file) { if (!$file->isDir()) { $filePath = $file->getRealPath(); $relativePath = substr($filePath, strlen($rootPath) + 1); $zip->addFile($filePath, $relativePath); } } $zip->close();
2。压缩整个文件夹删除除“important.txt”之外的所有文件:
$rootPath = rtrim($rootPath, '\/'); $rootPath = realpath('folder-to-zip'); $zip = new ZipArchive(); $zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE); $filesToDelete = array(); $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($files as $file) { if (!$file->isDir()) { $filePath = $file->getRealPath(); $relativePath = substr($filePath, strlen($rootPath) + 1); $zip->addFile($filePath, $relativePath); if ($file->getFilename() != 'important.txt') { $filesToDelete[] = $filePath; } } } $zip->close(); foreach ($filesToDelete as $file) { unlink($file); }
以上是如何使用 PHP 压缩整个文件夹并选择性地删除其内容?的详细内容。更多信息请关注PHP中文网其他相关文章!