问题描述
我正在尝试使用php显示目录中的所有文件和文件夹
Hi I am trying to show all files and folders in a dir with php
例如
Dir:系统/信息/
文件夹-用户
来自用户的文件-User1.txt
Files From User - User1.txt
来自用户的文件-User2.txt
Files From User - User2.txt
来自用户的文件-User3.txt
Files From User - User3.txt
来自用户的文件-User4.txt
Files From User - User4.txt
文件夹-播放器
播放器中的文件-Player1.txt
Files From Players - Player1.txt
播放器中的文件-Player2.txt
Files From Players - Player2.txt
播放器中的文件-Player3.txt
Files From Players - Player3.txt
播放器中的文件-Player4.txt
Files From Players - Player4.txt
有人可以带我走在正确的街道上吗
Can someone lead me down the right street please
谢谢
推荐答案
PHP 5具有 RecursiveDirectoryIterator
.
PHP 5 has the RecursiveDirectoryIterator
.
该手册有一个基本示例:
The manual has a basic example:
<?php
$directory = '/system/infomation/';
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
while($it->valid()) {
if (!$it->isDot()) {
echo 'SubPathName: ' . $it->getSubPathName() . "\n";
echo 'SubPath: ' . $it->getSubPath() . "\n";
echo 'Key: ' . $it->key() . "\n\n";
}
$it->next();
}
?>
编辑-这是一个稍微高级的示例(仅略有增加),它产生的输出类似于您想要的输出(即文件夹名和文件名).
Edit -- Here's a slightly more advanced example (only slightly) which produces output similar to what you want (i.e. folder names then files).
// Create recursive dir iterator which skips dot folders
$dir = new RecursiveDirectoryIterator('./system/information',
FilesystemIterator::SKIP_DOTS);
// Flatten the recursive iterator, folders come before their files
$it = new RecursiveIteratorIterator($dir,
RecursiveIteratorIterator::SELF_FIRST);
// Maximum depth is 1 level deeper than the base folder
$it->setMaxDepth(1);
// Basic loop displaying different messages based on file or folder
foreach ($it as $fileinfo) {
if ($fileinfo->isDir()) {
printf("Folder - %s\n", $fileinfo->getFilename());
} elseif ($fileinfo->isFile()) {
printf("File From %s - %s\n", $it->getSubPath(), $fileinfo->getFilename());
}
}
这篇关于如何在目录中列出文件和文件夹(PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!