PHP readfile or file_get_contents in a loop

2019-07-16 13:14发布

问题:

there may be other ways to do this but I'm looking for an fairly easy set-up because it's basically a one-time process.

I have 50 state directories with a handful of txt files in each one.

I want to step into each directory, "read" each file (and then do a mysql insert of each file)

I've tried a few variations, but each time I try to loop through and use readfile or file_get_contents it breaks after the first file and I get failed to open stream: errors on the remainder of the list.

I've searched for the pitfalls of using these functions in a loop expecting many reasons why not to, but not getting answers.

thanks came back to add example code - I see there is an answer listed so I 'll check that out also. (none of this is mine, I simply found a function to capture the file list)


    function listFilesInDir($start_dir)
        {

        /*
        returns an array of files in $start_dir (not recursive)
        */

        $files = array();
        $dir = opendir($start_dir);
        while(($myfile = readdir($dir)) !== false)
                {
                if($myfile != '.' && $myfile != '..')
                    {
                        $files[] = $myfile;
                     }
                }
        closedir($dir);
        return $files;
        }


        $dir = 'path/to/files';
        $Docs = listFilesInDir($dir);

        foreach($Docs as $key => $fileName)
        {

        // HERE IS WHERE I TRIED THE file_get_contents
        $content = file_get_contents($fileName);

        //even doing an echo as a test would break it after the first file
        echo $content;

        //ultimately I would just do INSERT INTO here for mysql




        }

回答1:

Some variation of the below is what i would use. YMMV depending on what you're doing. If you post your code we can address your specific implementation instead of just providing alternate solutions :-)

$dir = new DirectoryIterator('/path/to/states');
foreach($dir as $file)
{
  if(!$file->isDot() && $file->isFile() && strpos($file->getFilename(), '.txt') !== false)
  {
     $content = file_get_contents($file->getPathname());
     if($content)
     {
        // do your insert code
     }
  }
}