//php 递归实现遍历 用dir 返回对象 <? function loop($dir){ $mydir =dir($dir); //以对象的形式访问 while($file = $mydir ->read()){ //目录中有隐藏文件'.'和'..' 遍历的时候须要注意 if((is_dir("$dir/$file")) && ($file!=".") && ($file!="..")){ echo $file.'</br>'; loop("$dir/$file"); //递归循环 }else{ if($file!=".." && $file!="."){ echo $file."</br>"; } } } } loop(dirname(__FILE__)); //dirname 去掉文件名返回目录名
非递归处理遍历目录php
思路: 首先建立一个数组,由于第一次传的是一个去掉文件名的目录名(如 c://wamp/www/php)数组
进行foreach 循环 因此第一次把C://wamp/www/php 下的所有文件都放入到了 数组中/只够进行 while大循环 每次输出数组的最后一个,当文件为目录的时候在此进行foreach循环ide
知道最后一个值时count($list)值为0 退出循环oop
function scanAll($dir) { $list = array(); $list[] = $dir; while (count($list) > 0) { // var_dump($list); //弹出数组最后一个元素 $file = array_pop($list); //处理当前文件 echo $file."</br>"; //若是是目录 if (is_dir($file)){ $children = scandir($file); var_dump($children); foreach ($children as $child){ if ($child !== '.' && $child !== '..'){ $list[] = $file.'/'.$child; } } } } } scanAll(dirname(__FILE__));
PHP SPL 实现 遍历文件夹的文件spa
$path = dirname(__FILE__)."\\"; // 路径 echo $path."</br>"; $directory = new RecursiveDirectoryIterator($path); //The RecursiveDirectoryIterator provides an interface for iterating recursively over filesystem directories. $recursive = new RecursiveIteratorIterator($directory,RecursiveIteratorIterator::SELF_FIRST); //各项都包含,例如递归文件夹就会连同子文件夹名称也做为其中项输出,顺序是先父后子 foreach($recursive as $file) { echo str_repeat("\t", $recursive->getDepth()); // 获取当前的深度 if ($file->isDir()) { echo DIRECTORY_SEPARATOR; //DIRECTORY_SEPARATOR是php的内部常量,用于显示系统分隔符的命令,不须要任何定义与包含便可直接使用 } echo $file->getBasename(); //Gets the base name of the file if ($file->isFile()) { echo "(" . $file->getSize() . "bytes)"; } else if ($file->isLink()) { //判断是不是一个符号连接 echo "(symlink)"; } echo "</br>"; } //echo $path;