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

匆匆过客 提交于 2020-01-01 06:26:08

问题


I'm trying to get the behavior like the "tree" command on linux or unix systems where the function returns a list or array of directories in its full path.

Example

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

etc .... etc...


回答1:


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

Update #1:

If you want empty directories to be listed as well, use RecursiveIteratorIterator::CHILD_FIRST

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



回答2:


Checkout PHP's Recursivedirectoryiterator. It will do what you need, and it has some nice examples.



来源:https://stackoverflow.com/questions/6016883/how-to-walk-a-directory-recursively-returning-the-full-path-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!