0

I'm trying to pull the names of the subdirectories of a directory into an array. I've tried a few different things. What am I doing wrong here?

I pulled this little function off of the php scandir() documentation page.


$data_dir = 'path/to/data_directory/';

function dirToArray( $data_dir ) { 

   $result = array(); 

   $cdir = scandir( $data_dir );          // line 19
   foreach ($cdir as $key => $value) 
   { 
      if (!in_array($value,array(".",".."))) 
      { 
         if (is_dir($data_dir . DIRECTORY_SEPARATOR . $value)) 
         { 
            $result[$value] = dirToArray($data_dir . DIRECTORY_SEPARATOR . $value); 
         } 
         else 
         { 
            $result[] = $value; 
         } 
      } 
   } 

   return $result; 
}

$data_dir_array = dirToArray( $data_dir );

print_r( $data_dir_array );

ouput

Warning: scandir(/Users/alexcory/Library/Application\ Support/Alfred\ 2/Workflow\ Data): failed to open dir: No such file or directory in /Users/alexcory/Library/Application Support/Alfred 2/Alfred.alfredpreferences/workflows/user.workflow.36DE4754-2C41-4A38-BA8A-FF48D97C6371/open_data.php on line 19

Warning: scandir(): (errno 2): No such file or directory in /Users/alexcory/Library/Application Support/Alfred 2/Alfred.alfredpreferences/workflows/user.workflow.36DE4754-2C41-4A38-BA8A-FF48D97C6371/open_data.php on line 19

Warning: Invalid argument supplied for foreach() in /Users/alexcory/Library/Application Support/Alfred 2/Alfred.alfredpreferences/workflows/user.workflow.36DE4754-2C41-4A38-BA8A-FF48D97C6371/open_data.php on line 20 Array ( )

Alex Cory
  • 10,635
  • 10
  • 52
  • 62
  • 1
    possible duplicate of [How to read a list of files from a folder using PHP?](http://stackoverflow.com/questions/720751/how-to-read-a-list-of-files-from-a-folder-using-php) – Jeff Lambert Mar 10 '14 at 01:31
  • 1
    you just give a not existent directory.. (but it may be a directory name problem (spaces)) – Rufinus Mar 10 '14 at 01:33
  • First of all, i would remove the line: $data_dir = 'path/to/data_directory/'; since you are declaring a argument with this same name. Secondly, can you check that the directory actually exists and that it has the correct permissions (it looks like it failed to open the directory). Thirdly, add some kind of error checking to check $result, it looks like it is returning an error (probably because it can't open the directory). – Nick Weedon Mar 10 '14 at 01:35

0 Answers0