Reputation: 35
I'm trying to list directories recrusively in PHP using the RecursiveDirectoryIterator and RecursiveIteratorIterator, but the thing is, i need to ignore some directories and files within..
This is what i have so far..
// 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 />';
}
I've tried different ways to check if the directory/file is in the array, but or it doesn't work, or the directory is not ignored completly...
This an example of the directory structure
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
Is this possible, or i need to use the old fashion way to recursive list directories/files in PHP ?
Thanks !
Upvotes: 3
Views: 3080
Reputation: 1
Here is another approach using 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
Upvotes: 0
Reputation: 95101
You should always use Full Path
since you are combining file and folder
$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 />';
}
Upvotes: 3