How to recursively iterate through files in PHP?

后端 未结 7 1820
走了就别回头了
走了就别回头了 2021-02-12 16:47

I have set up a basic script that is posting an array of paths to find template files inside them; currently it\'s only searching two levels deep and I\'m having some troubles g

7条回答
  •  [愿得一人]
    2021-02-12 17:13

    Alternative of my previous answer :

    $dir = 'components';
    function getFiles($dir, &$results = array(), $filename = 'template.html'){
        $files = scandir($dir);
        foreach($files as $key => $value){
            $path = realpath($dir.'/'.$value);
            if(!is_dir($path)) {
                if($value == $filename)         
                    $results[] = $path;         
            } else if($value != "." && $value != "..") {
                getFiles($path, $results);
            }
        }
        return $results;
    }
    echo '
    '.print_r(getFiles($dir), 1).'
    ';

    OUTPUT :

    Array
    (
        [0] => /web/practise/php/others/test7/components/side/second/template.html
        [1] => /web/practise/php/others/test7/components/side/second/third/template.html
        [2] => /web/practise/php/others/test7/components/side/template.html
        [3] => /web/practise/php/others/test7/components/template.html
    )
    

提交回复
热议问题