效果
保持目录结构,压缩整个文件夹为zip包
完整代码
<?php /** * 压缩整个文件夹为zip文件 */ function make_zip_file_for_folder ($zip_path = '', $folder_path = '') { // Get real path for our folder $rootPath = realpath($folder_path); // Initialize archive object $zip = new ZipArchive(); $zip->open($zip_path, 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(); }
使用方法
//RecursiveIteratorIterator 递归获取文件树(列表) //$zip->addFile($filePath, $relativePath); 逐个添加文件到zip压缩包 $zip_file = '/var/www/abc.zip'; $zip_dir = '/var/www/abc/'; make_zip_file_for_folder($zip_file, $zip_dir);
标签:php,RecursiveIteratorIterator,zip,filePath,ZipArchive,file,var,PHP From: https://www.cnblogs.com/mygaoge/p/17070326.html