問題:
如何使用 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中文網其他相關文章!