在工作中会有遍历目录与子目录文件的时候,请看以下代码
function get_allfiles($path,&$files) {
if(is_dir($path)){ //是否为目录
$dp = dir($path);
while ($file = $dp ->read()){
if($file !="." && $file !=".."){
get_allfiles($path."/".$file, $files); //递归
}
}
$dp ->close();
}
if(is_file($path)){ //如果文件正常
$files[] = $path;
}
}
function get_filenamesbydir($dir){
$files = array();
get_allfiles($dir,$files);
return $files;
}
$paths = 'E:/我的文件';
$paths = iconv( 'UTF-8','GB2312', $paths); //中文需要转码
$filenames = get_filenamesbydir($paths);
foreach ($filenames as $key => $value) {
$value = iconv('GB2312', 'UTF-8', $value); //打印时在转回去
echo $value . "<br />";
}