John Davidson

php - RecursiveIterator not working as expected

0 comments
Message:


Here is my function:


protected function getContents($absoluteDirectoryPath = false, $recursive = false, $filter = "/.$/") {
if(!$absoluteDirectoryPath) return false;
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($absoluteDirectoryPath));
$files = new RegexIterator($iterator, $filter);
return $iterator;
}

And i call it like this:


$pageFiles = $this->getContents($pagepath);

foreach($pageFiles as $file) {
echobr("PageFile: " . $file->fileName);
}

This is the error I get:


Notice: Undefined property: SplFileInfo::$fileName


If I var_dump $pageFiles I get this:


object(DirectoryIterator)#5 (4) {
["pathName":"SplFileInfo":private]=>
string(68) "/home/domain/example/public/home/home.php"
["fileName":"SplFileInfo":private]=>
string(12) "home.php"
["glob":"DirectoryIterator":private]=>
bool(false)
["subPathName":"RecursiveDirectoryIterator":private]=>
string(0) ""
}

Whats going on? Why can't I loop through the results? There are 4 files in this directory and I should be able to output the filename.



My Answer:
null) {
$contents = array();

if ($absoluteDirectoryPath) {
$directoryIterator = new RecursiveDirectoryIterator($absoluteDirectoryPath);
$iterator = new RecursiveIteratorIterator($directoryIterator);

foreach ($iterator as $file) {
if ($filter && !preg_match($filter, $file->getFilename())) {
continue;
}

$contents[] = $file->getPathname();
}
}

return $contents;
}

This function should return an array of file paths within a given directory. If the $recursive parameter is set to true, it should also include files from subdirectories. The $filter parameter allows for filtering files based on a regular expression.

If this function is not working as expected, there may be an issue with the way the RecursiveIteratorIterator is being used. Make sure that the RecursiveDirectoryIterator is properly initialized with the directory path and that the RecursiveIteratorIterator is correctly iterating over the files.

Additionally, check that the regular expression filter is working as expected and that it is correctly excluding files that do not match the filter.

If you are still experiencing issues, try debugging the function by adding print statements or using a debugger to step through the code and see where the problem may be occurring.

Rate this post

3 of 5 based on 4143 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us