php 获取目录内的所有文件

利用opendir readdir 及递归的方法 获取目录下的所有文件内容
function fileList($dir, $level = 0) {
    $fpdir = opendir($dir);
    while($line = readdir($fpdir)) {
        if(strcmp($line, '.') == 0 || strcmp($line, '..') == 0 ) {continue;}
        $encode = mb_detect_encoding($line);
        echo str_pad('', $level*4, '-', STR_PAD_LEFT) . iconv($encode, "utf-8", $line),"<br />";
        echo "\n";
        if(substr($dir, -1) != '/') {
            $newDir = $dir . '/' . $line;                
        } else {
            $newDir = $dir . $line;
        }
        
        if(is_dir($newDir)){            
            fileList($newDir, $level+1);
        }
    }
    
    
    closedir($fpdir);
    
}

2、利用函数 glob  和递归的方法 获取

function fileList($dir) {
    $dir = str_replace('\\', '/', $dir);  //替换windows的默认斜线
    if(substr($dir, -1) != '/') {         //对路径进行补全
        $dir .= '/*';
    } else {
        $dir .= '*';        
    }
    $list = glob($dir . '*');            //获取目录下的所有文件
    $len = count($list);
    for($i=0; $i<$len; $i++) {
        $encode = mb_detect_encoding($list[$i]);   //获取当前子字符串的编码
        
        echo iconv($encode, 'utf-8', $list[$i]),'<br>';  //将字符串的编码转化为 utf-8
        if(is_dir($list[$i])) {
            fileList($list[$i]);
        }
    }    
    
}


这两种方法种都用到了函数  mb_dectect_encoding()  函数,这个是php的扩展mb_string,所以这个扩展一定要开启。

你可能感兴趣的:(php 获取目录内的所有文件)