如何在 PHP 中以递归方式返回完整路径的目录


How to walk a directory recursively returning the full path in PHP?

我正在尝试在 linux 或 unix 系统上获取类似于"tree"命令的行为,其中函数在其完整路径中返回目录列表或数组。

~/
~/Pictures
~/Movies
~/Downloads
~/Documents
~/Documents/work
~/Documents/important
~/Documents/bills
~/Music
~/Music/80s/

等。。。。等。。。

foreach (new RecursiveIteratorIterator (new RecursiveDirectoryIterator ('.')) as $x)
{
        echo $x->getPathname (), "'n";
}

更新#1:

如果还希望列出空目录,请使用递归迭代器迭代器::CHILD_FIRST

foreach (new RecursiveIteratorIterator (new RecursiveDirectoryIterator ('.'), RecursiveIteratorIterator::CHILD_FIRST) as $x)
{
    echo $x->getPathname (), "'n";
}

Checkout PHP 的递归目录迭代器。它会做你需要的,它有一些很好的例子。