以递归方式列出PHP中的目录/文件并忽略数组中的目录

时间:2012-10-08 17:36:56

标签: php recursion

我正在尝试使用RecursiveDirectoryIterator和RecursiveIteratorIterator在PHP中重新列出目录,但问题是,我需要忽略一些目录和文件..

这是我到目前为止所拥有的......

// Define here the directory you have platform installed.
//
$path = 'testing';

// List of directories / files to be ignored.
//
$ignore_new = array(
# Directories
#
'.git',
'testing/dir1',
'testing/dir2',
'testing/dir3',
'testing/dir8',
'public',

# Files
#
'.gitignore',
'.gitmodules',
'.CHANGELOG.md',
'.README.md',
);


$ite = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);
foreach (new RecursiveIteratorIterator($ite) as $filename => $object)
{
    echo $filename . '<br />';
}

我尝试了不同的方法来检查目录/文件是否在数组中,但是它不起作用,或者目录没有被完全忽略......

这是目录结构的一个例子

testing\
testing\.git
testing\.git\files & directories
testing\testing\dir1
testing\testing\dir2
testing\testing\dir3
testing\testing\dir8
testing\.gitignore
testing\.gitmodules
testing\CHANGELOG.md
testing\README.md

这是可能的,还是我需要使用旧方式来递归列表目录/文件?

谢谢!

2 个答案:

答案 0 :(得分:3)

由于您要合并文件和文件夹

,因此应始终使用Full Path
$path = __DIR__;

// List of directories / files to be ignored.
//
$ignoreDir = array('1.MOV.xml','.git','testing/dir1','testing/dir2','testing/dir3','testing/dir8','public');

/**
 * Quick patch to add full path to Ignore
 */
$ignoreDir = array_map(function ($var) use($path) {
    return $path . DIRECTORY_SEPARATOR . $var;
}, $ignoreDir);

$ite = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);
foreach ( new RecursiveIteratorIterator($ite) as $filename => $object ) {

    if (in_array($filename, $ignoreDir))
        continue;

    echo $filename . '<br />';
}

答案 1 :(得分:0)

这是使用RecursiveCallbackFilterIterator的另一种方法:

<?php

$f_filter = function ($o_info) {
   $s_file = $o_info->getFilename();
   if ($s_file == '.git') {
      return false;
   }
   if ($s_file == '.gitignore') {
      return false;
   }
   return true;
};

$o_dir = new RecursiveDirectoryIterator('.');
$o_filter = new RecursiveCallbackFilterIterator($o_dir, $f_filter);
$o_iter = new RecursiveIteratorIterator($o_filter);

foreach ($o_iter as $o_info) {
   echo $o_info->getPathname(), "\n";
}

https://php.net/class.recursivecallbackfilteriterator