This article is mainly to share with you several methods of PHP folder traversal, I hope to help everyone.
Function
function DirTree () {
if (!is_dir ($path)) return []; $files = []; $dir = Opendir ($path); while ($file = Readdir ($dir)) { if ($file = = '. ' | | $file = = ' ... ') continue; $new _path = Trim ($path, '/'). ' /'. Trim ($file, '/'); $files [] = $new _path; if (Is_dir ($new _path)) { $files = Array_merge ($files, $this->ergodicdir2 ($new _path));
}
}
Closedir ($dir); return $files;
}
Directory Class
function DirTree () {
if (!is_dir ($path)) return []; $files = []; $dir _h = dir ($path); while ($file = $dir _h->read ()) { if ($file = = '. ' | | $file = = ' ... ') continue; $new _path = Trim ($path, '/'). ' /'. Trim ($file, '/'); $files [] = $new _path; if (Is_dir ($new _path)) { $files = Array_merge ($files, $this->ergodicdir3 ($new _path));
}
} $dir _h->close (); return $files;
}
Iterators
function DirTree () {
if (!is_dir ($path)) return []; $files = []; $dir = new \directoryiterator ($path); foreach ($dir as $key = + $file) {if ($file->getfilename () = = '. ' | | $file->getfilename () = = ') {continue;
} $files [] = $file->getpathname (); if ($file->isdir ()) {$files = Array_merge ($files, $this->ergodicdir5 ($file->getpathname ()));
}
} return $files;
}