RecursiveDirectoryIterator删除Dot文件夹

时间:2015-01-15 02:12:28

标签: php

目前我有以下代码,以便能够在下面的代码中设置标记,这样我可以使用::SKIP_DOTS

代码:

  $folder = 'images/banner_img';?>

    <?php foreach( new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folder)) as $filename): ?>
      <?php $fileTypes = array("db"); 
            $fileType  = pathinfo($filename,PATHINFO_EXTENSION);

            if(!in_array(strtolower($fileType), $fileTypes)):?>


         <img src="<?php echo $filename; ?>" alt="" title="" data-thumb="<?php echo $filename;?>" />

       <?php endif;?>

    <?php endforeach;?>

2 个答案:

答案 0 :(得分:6)

RecursiveDirectoryIterator::SKIP_DOTS as an option (in the second parameter)设置为new RecursiveDirectoryIterator()应该足以使用您当前的代码。

使用PHP 5.3+,您也可以将RecursiveDirectoryIterator声明为自己的变量,然后在该变量上调用方法:

$iterator = new RecursiveDirectoryIterator($folder);
$iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
// Still need to pass $iterator to a RecursiveIteratorIterator...

setFlags()是一种方法inherited from the FilesystemIterator base class

但是由于您已经在使用模板格式foreach: / endforeach;样式,因此在嵌套声明中执行它而不是使用其他变量是有意义的。

<!-- Instead, stick with your current iterator declaration and -->
<!-- add RecursiveDirectoryIterator::SKIP_DOTS as the 2nd param to its constructor -->
<?php foreach( new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folder, RecursiveDirectoryIterator::SKIP_DOTS)) as $filename): ?>
<!-------------------------------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -->

答案 1 :(得分:0)

标志::SKIP_DOTS在某些计算机上引发错误GET / - Uncaught Error: Undefined class constant 'SKIP_DOTS'

替代下面将跳过隐藏的文件夹,隐藏的文件和导航点. ..

$cwd = './targetdir';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($cwd), RecursiveIteratorIterator::SELF_FIRST );

// Skip hidden directories and hidden files
foreach ( $iterator as $path ) {
  if(!$path->isFile()) continue;
  $dirname = explode("/",$path->__toString());
  $dirname = substr($dirname[count($dirname)-2], 0, 1);
  if($dirname === ".") continue;
  if(substr($path->getFilename(), 0, 1) === ".") continue;

  if ($path->isDir()) {
      print($path->__toString() . "<br>");
   } else {
      print($path->__toString() . "<br>");
  }
}