PHP iterates through a folder and compresses it into a zip
PHP code
Private Function Zip ($path, $zipFile) {$zip =new ziparchive (); $zip->open ($zipFile, ziparchive::create);//Create an empty zip file $this->addfiletozip ($path, $zip); } Private Function Addfiletozip ($path, ziparchive $zip, $root = ") {if (!is_dir ($path)) {return false; } if (! $root) {$root = $path; } if (Strpos ($path, $root)!==0) {$root = $path; } $handler =opendir ($path); Opens the current folder specified by $path. while (($filename =readdir ($handler))!==false) {if ($filename! = "." && $filename! = "...") {//Folder file name is '. ' and '. ', do not operate on them if (Is_dir ($path. ") /". $filename)) {//If an object read is a folder, the recursive $this->addfiletozip ($path." /". $filename, $zip, $root); }else{//Add files to the Zip object $filenameWithPath = $path. " /". $filename; $localFileName = substr ($filenameWithPath, strlen ($root)); $zip->addfile ($filenameWithPath, $locAlfilename); }}} @closedir ($handler); }
Refactoring code with yield
PHP code
Private Function Zipfolder ($folder, $zipFile) {$zip =new ziparchive (); $zip->open ($zipFile, ziparchive::create);//Create an empty zip file foreach ($this->yieldfile ($folder) as $file) { $localFileName = substr ($file, strlen ($folder)); $zip->addfile ($file, $localFileName); }} Private Function Yieldfile ($path) {if (Is_dir ($path)) {$handler = Opendir ($path); while (($filename =readdir ($handler))!==false) {if ($filename! = "." && $filename! = "...") {//Folder file name is '. ' and '. ', do not operate on them if (Is_dir ($path. ") /". $filename)) {//If an object being read is a folder, then the recursive foreach ($this->yieldfile ($path." /". $filename) as $file) {yield $file; }}else{//Add the file to the Zip object $file = $path. " /". $filename; Yield $file; }}} closedir ($handLER); } }
Code execution
PHP code
Public Function Anyzip () {for ($i =0; $i <6; $i + +) { $start = Microtime (true); $toPath = ' d:/unzip '; $this->zipfolder ($toPath, ' d:/zip/123.zip '); $end = Microtime (true); Echo ' |zipfolder-delay: '. ($end-$start); $start = Microtime (true); $toPath = ' d:/unzip '; $this->zip ($toPath, ' d:/zip/124.zip '); $end = Microtime (true); Echo ' |zip-delay: '. ($end-$start). '
'; } }
|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
There is little difference between using yield recursion and normal recursive execution time, and the main benefit is to split data acquisition and data processing, easier to understand and reuse