PHP fopen or file_get_contents reading CSV files with fgetcsv

927 Views Asked by At

I have a issue. In my original code I opened a file with:

$file = fopen ("files/bla1.exp" , "r" );

And after opening the file, I want to read the CSV line by line with:

$aCsvLine = fgetcsv($file,"0",";",'"');

That works fine, but now the problem. Now I want to open multiple files and then read line by line with fgetcsv.

This is nog working:

if($sDate ==  "2022-07-18" || $sDate ==  "2022-07-19" || $sDate ==  "2022-07-20" || $sDate ==  "2022-07-21" || $sDate ==  "2022-07-22")
      {
        $file = fopen ("files/bla1.exp" , "r" );
        $file = fopen ("files/bla2.exp" , "r" );
        $file = fopen ("files/bla3.exp" , "r" );
      }

And this from my other post is also not working, because of missing the handle:

    $file = '';
if ($sDate ==  "2022-07-18" || $sDate ==  "2022-07-19" || $sDate ==  "2022-07-20" || $sDate ==  "2022-07-21" || $sDate ==  "2022-07-22")
      {
        $file .= file_get_contents("files/bla1.exp");
        $file .= file_get_contents("files/bla2.exp");
        $file .= file_get_contents("files/bla3.exp");
      }

How can I first open my csv files and append them to one file and the read it line by line. I hope I made my question clear.

1

There are 1 best solutions below

0
Phil On

Create an array of filenames and iterate that. In each iteration, open the file and start reading from it using fgetcsv().

$files = ['files/bla1.exp', 'files/bla2.exp', 'files/bla3.exp'];
$allRows = [];

foreach ($files as $file) {
    $fh = fopen($file, 'rb');
    while (($row = fgetcsv($fh, 0, ';', '"')) !== false) {
        $allRows[] = $row; // ¯\_(ツ)_/¯
    }
    fclose($fh);
}