//php 递归实现遍历 用dir 返回对象
function loop($dir){
$mydir =dir($dir); //以对象的形式访问
while($file = $mydir ->read()){
//目录中有隐藏文件'.'和'..' 遍历的时候需要注意
if((is_dir("$dir/$file")) && ($file!=".") && ($file!="..")){
echo $file.'';
loop("$dir/$file"); //递归循环
}else{
if($file!=".." && $file!="."){
echo $file."";
}
}
}
}
loop(dirname(__FILE__)); //dirname 去掉文件名返回目录名
非递归处理遍历目录
思路: 首先创建一个数组,因为第一次传的是一个去掉文件名的目录名(如 c://wamp/www/php)
进行foreach 循环 所以第一次把C://wamp/www/php 下的全部文件都放入到了 数组中/只够进行 while大循环 每次输出数组的最后一个,当文件为目录的时候在此进行foreach循环
知道最后一个值时count($list)值为0 退出循环
function scanAll($dir)
{
$list = array();
$list[] = $dir;
while (count($list) > 0)
{
// var_dump($list);
//弹出数组最后一个元素
$file = array_pop($list);
//处理当前文件
echo $file."";
//如果是目录
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 实现 遍历文件夹的文件
$path = dirname(__FILE__)."\\"; // 路径
echo $path."";
$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 "";
}
//echo $path;