dongzhuzhou4504
dongzhuzhou4504
2015-12-07 11:20

递归地要求所有文件

已采纳

I am trying to add all files in my project recursively, for this I have used this function:

<?php

function RequireFiles()
{
    $directory = new RecursiveDirectoryIterator(abspath . "lib/");
    $recIterator = new RecursiveIteratorIterator($directory);

    foreach ($recIterator as $item)
    {
        print $item->getPathname() . "<br />";
        //include $item->getPathname();
    }
}

?>

taken from here with minor changes.

My problem is that my output looks like this:

E:/projects/php/project/project/lib.
E:/projects/php/project/project/lib..
E:/projects/php/project/project/lib\class.
E:/projects/php/project/project/lib\class..
E:/projects/php/project/project/lib\class\Log.php
E:/projects/php/project/project/lib\trait.
E:/projects/php/project/project/lib\trait..
E:/projects/php/project/project/lib\trait\SetLink.php
E:/projects/php/project/project/lib\trait\MysqliEsp.php
E:/projects/php/project/project/lib\arrays.
E:/projects/php/project/project/lib\arrays..
E:/projects/php/project/project/lib\arrays\tables.php

I do not want to have the \. and \.. on the end and have looked for an answer for this for a while and cannot find out how to rid myself of these little terrors!

Can someone help me to fix this or point me in the direction of a Q&A that does?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • douzhu3654 douzhu3654 6年前

    Just pass the flag FilesystemIterator::SKIP_DOTS in the constructor, e.g.

    $directory = new RecursiveDirectoryIterator(abspath . "lib/"
                                                , FilesystemIterator::SKIP_DOTS);
    点赞 评论 复制链接分享
  • dtzh131555 dtzh131555 6年前

    Try checking the name ($key) and discarding what you don't want:

    foreach ($recIterator as $k=>$item)
    {
        if ($k == '.' || $k == '..') { continue; }
        print $item->getPathname() . "<br />";
        //include $item->getPathname();
    }
    
    点赞 评论 复制链接分享
  • doudong4532 doudong4532 6年前

    The class SplFileInfo (that is what you get from RecursiveIteratorIterator and RecursiveDirectoryIterator) has a method called isFile().

    You can just add if( !$item->isFile() ) continue;to your foreach:

    foreach ( $recIterator as $item ) {
        if( !$item->isFile() ) continue;
        print $item->getPathname() . "<br />";
        //include $item->getPathname();
    }
    
    点赞 评论 复制链接分享

为你推荐