当前位置:Gxlcms > PHP教程 > phpyield初体验,递归遍历文件夹并压缩

phpyield初体验,递归遍历文件夹并压缩

时间:2021-07-01 10:21:17 帮助过:34人阅读

php遍历一个文件夹并压缩到zip

Php代码

  1. private function zip($path,$zipFile){
  2. $zip=new ZipArchive();
  3. $zip->open($zipFile,ZipArchive::CREATE);//创建一个空的zip文件
  4. $this->addFileToZip($path,$zip);
  5. }
  6. private function addFileToZip($path,ZipArchive $zip,$root=''){
  7. if(!is_dir($path)){
  8. return false;
  9. }
  10. if(!$root){
  11. $root= $path;
  12. }
  13. if(strpos($path,$root)!==0){
  14. $root= $path;
  15. }
  16. $handler=opendir($path); //打开当前文件夹由$path指定。
  17. while(($filename=readdir($handler))!==false){
  18. if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’,不要对他们进行操作
  19. if(is_dir($path."/".$filename)){// 如果读取的某个对象是文件夹,则递归
  20. $this->addFileToZip($path."/".$filename, $zip,$root);
  21. }else{ //将文件加入zip对象
  22. $filenameWithPath = $path."/".$filename;
  23. $localFileName = substr($filenameWithPath,strlen($root));
  24. $zip->addFile($filenameWithPath,$localFileName);
  25. }
  26. }
  27. }
  28. @closedir($handler);
  29. }

使用yield重构代码

Php代码

  1. private function zipFolder($folder,$zipFile){
  2. $zip=new ZipArchive();
  3. $zip->open($zipFile,ZipArchive::CREATE);//创建一个空的zip文件
  4. foreach($this->yieldFile($folder) as $file){
  5. $localFileName = substr($file,strlen($folder));
  6. $zip->addFile($file,$localFileName);
  7. }
  8. }
  9. private function yieldFile($path){
  10. if(is_dir($path)){
  11. $handler = opendir($path);
  12. while(($filename=readdir($handler))!==false){
  13. if($filename != "." && $filename != "..") {//文件夹文件名字为'.'和‘..’,不要对他们进行操作
  14. if(is_dir($path."/".$filename)){// 如果读取的某个对象是文件夹,则递归
  15. foreach($this->yieldFile($path."/".$filename) as $file){
  16. yield $file;
  17. }
  18. }else{ //将文件加入zip对象
  19. $file = $path."/".$filename;
  20. yield $file;
  21. }
  22. }
  23. }
  24. closedir($handler);
  25. }
  26. }

代码执行

Php代码

  1. public function anyZip(){
  2. for($i=0;$i<6;$i++) {
  3. $start = microtime(true);
  4. $toPath = 'D:/unzip';
  5. $this->zipFolder($toPath, 'd:/zip/123.zip');
  6. $end = microtime(true);
  7. echo '|zipFolder-delay:' . ($end - $start);
  8. $start = microtime(true);
  9. $toPath = 'D:/unzip';
  10. $this->zip($toPath, 'd:/zip/124.zip');
  11. $end = microtime(true);
  12. echo '|zip-delay:' . ($end - $start) . '<br>';
  13. }
  14. }

|zipFolder-delay:1.6427090167999|zip-delay:1.6077039241791
|zipFolder-delay:1.6132049560547|zip-delay:1.6287071704865
|zipFolder-delay:1.6342070102692|zip-delay:1.6152048110962
|zipFolder-delay:1.6917150020599|zip-delay:1.6022040843964
|zipFolder-delay:1.6297070980072|zip-delay:1.7262189388275
|zipFolder-delay:1.5997030735016|zip-delay:1.5892019271851

使用yield递归和正常的递归执行时间差距不大,主要好处是将数据获取和数据处理拆分开,更易理解和复用

人气教程排行