How to recursively iterate through files in PHP?

后端 未结 7 1834
走了就别回头了
走了就别回头了 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:24

    Here is a generic solution:

    function parseDir($dir, &$files=array(), $extension=false){
    
    if(!is_dir($dir)){
        $info =  pathinfo($dir);
        // add all files if extension is set to false
        if($extension === false || (isset($info['extension']) && $info['extension'] === $extension)){
            $files[] = $dir;
        }
    }else{
        if(substr($dir, -1) !== '.' && $dh =  opendir($dir)){
            while($file = readdir($dh)){
                parseDir("$dir/$file", $files, $extension);
            }
        }
    }
     }
    
    $files = array();
    parseDir('components', $files, 'html');
    var_dump($files);
    

    OUTPUT

    php parseDir.php 
    array(7) {
      [0]=>
      string(25) "components/template2.html"
      [1]=>
      string(29) "components/side/template.html"
      [2]=>
      string(30) "components/side/template2.html"
      [3]=>
      string(36) "components/side/second/template.html"
      [4]=>
      string(37) "components/side/second/template2.html"
      [5]=>
      string(42) "components/side/second/third/template.html"
      [6]=>
      string(43) "components/side/second/third/template2.html"
    }
    
    0 讨论(0)
提交回复
热议问题