使用PHP获取目录的层次结构

Cal*_*lum 9 php filesystems directory file

我正在尝试查找指定目录下的所有文件和文件夹

例如,我有/ home/user/stuff

我想回来

/home/user/stuff/folder1/image1.jpg
/home/user/stuff/folder1/image2.jpg
/home/user/stuff/folder2/subfolder1/image1.jpg
/home/user/stuff/image1.jpg
Run Code Online (Sandbox Code Playgroud)

希望这是有道理的!

Ste*_*ard 12

function dir_contents_recursive($dir) {
    // open handler for the directory
    $iter = new DirectoryIterator($dir);

    foreach( $iter as $item ) {
        // make sure you don't try to access the current dir or the parent
        if ($item != '.' && $item != '..') {
            if( $item->isDir() ) {
                // call the function on the folder
                dir_contents_recursive("$dir/$item");
            } else {
                // print files
                echo $dir . "/" .$item->getFilename() . "<br>";
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Tom*_*igh 5

foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $f) {
    echo "$f \r\n";   
}
Run Code Online (Sandbox Code Playgroud)