How to recursively iterate through files in PHP?

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

    PHP 5 introduces iterators to iterate quickly through many elements.

    You can use RecursiveDirectoryIterator to iterate recursively through directories.

    You can use RecursiveIteratorIterator on the result to have a flatten view of the result.

    You can use RegexIterator on the result to filter based on a regular expression.

     $directory_iterator = new RecursiveDirectoryIterator('.');
     $iterator       = new RecursiveIteratorIterator($directory_iterator);
     $regex_iterator = new RegexIterator($iterator, '/\.php$/');
     $regex_iterator->setFlags(RegexIterator::USE_KEY);
     foreach ($regex_iterator as $file) {
        echo $file->getPathname() . PHP_EOL;
     }
    

    With iterators, there are lot of ways to do the same thing, you can also use a FilterIterator (see the example on the page)

    For instance, if you want to select the files modified this week, you can use the following:

      $directory_iterator = new RecursiveDirectoryIterator('.');
      $iterator       = new RecursiveIteratorIterator($directory_iterator);
    
      class CustomFilterIterator extends FilterIterator {
           function accept() {
                $current=$this->getInnerIterator()->current();
                return ($current->isFile()&&$current->getMTime()>time()-3600*24*7);
           }
      }
    
      $filter_iterator=new CustomFilterIterator($iterator);
      foreach ($filter_iterator as $file) {
         echo $file->getPathname() . PHP_EOL;
      }
    

提交回复
热议问题