Home > Back-end >  Convert SplFileInfo Object To Array Problems
Convert SplFileInfo Object To Array Problems

Time:11-28

I have searched SO and went through all of them. Many don't seem to apply to my problem but supplied information that I tried to apply. Result was many parse errors. I can't seem to apply them correctly. This is my first use of iterators. So, after a few days trying I need help.

The original code was taken form the PHP manual. I turned it into a function and added the code to remove dot and dot dot entries (. and ..). I then added code to return an array of files so I can use it in a foreach statement. Problem is that I don't have access to the properties.

<?php
function getDirectoryListing($path)
{
 $dir_iterator = new RecursiveDirectoryIterator($path);
 $iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
 $files = array();
 foreach($iterator as $file)
 {
  if(strpos($file, ".", -1) !== false)
  {
   continue;
  } // Closing brace for if(strpos($file, ".", -1) !== false)
  $files[] = $file;
 } // Closing brace for foreach($iterator as $file)
 return $files;
}

$files = getDirectoryListing("I:\cef-inc.net/images/database/");
print_r($files);
?>

When I print_r $files I get:

Array ( [0] => SplFileInfo Object ( [pathName:SplFileInfo:private] => I:\cef-inc.net/images/database\calendar.ico [fileName:SplFileInfo:private] => calendar.ico ) )

When I echo $file in the foreach I get the pathName but not the fileName.

What do I need to do in the function to put everything in an array?

Thank you for looking,

Charles

CodePudding user response:

You get an array of SplFileInfo objects. You should use their getFilename() method to access their filename without the path. When you echo the object, you’re calling __tostring() method.

  •  Tags:  
  • php
  • Related