Rumah >pembangunan bahagian belakang >tutorial php >Bagaimana untuk Zip Folder Lengkap dan Secara Pilihan Padamkan Kandungannya Menggunakan PHP?
Soalan:
Bagaimana anda boleh membuat arkib ZIP bagi keseluruhan folder menggunakan PHP? Selain itu, bagaimanakah anda memadamkan semua kandungan folder selepas mengezipnya, tidak termasuk fail tertentu?
Jawapan:
1. Zip Seluruh Folder:
$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. Zip Seluruh Folder Padam Semua Fail Kecuali "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); }
Atas ialah kandungan terperinci Bagaimana untuk Zip Folder Lengkap dan Secara Pilihan Padamkan Kandungannya Menggunakan PHP?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!