PHP使用FilesystemIterator迭代器遍历目录
/**
* PHP高效遍历文件夹(大量文件不会卡死)
* @param string $path 目录路径
* @param integer $level 目录深度
*/
function fn_scandir($path = './', $level = 0) {
$file = new FilesystemIterator($path);
$filename = '';
$prefix = '';
$url = '';
foreach ($file as $fileinfo) {
$filename = $fileinfo->getFilename();
$filepath = $path . $filename;
// print_r($filepath);
// echo $filename;
// echo '||';
$prefix = $level > 0 ? ('|' . str_repeat('--', $level)) : '';
if ($fileinfo->isDir()) {
$filepath = $filepath . '/';
$url = '<a title="[dir] '.$filepath.'" href="?path=' . $filepath . '">' . $filename . '</a> [<a title="delete" href="?path=' . $filepath . '&action=del" onclick="return confirm(\'您确定要删除吗?\')">x</a>]';
// echo '<strong>' . $prefix . $url . '/</strong>' . '<br />';
} else {
$url = '<a title="[file] '.$filepath.'" href="?path=' . $filepath . '">' . $filename . '</a> [<a title="delete" href="?path=' . $filepath . '&action=del" onclick="return confirm(\'您确定要删除吗?\')">x</a>]';
// echo $prefix . $url . '<br />';
}
if ($fileinfo->isDir()) {
fn_scandir($filepath, $level + 1);
}
if(is_file($filepath)){
echo $filepath.'</br>';
}
}
}
fn_scandir('./files/');
踩过这个坑,还有下一个坑等着你,这一路就是给自己填坑,坑填多了,也就习惯了,直到这一路平坦了,也就无怨无悔了。