Search code examples
phpcsvsplfileobject

SplFileObject not reading CSV properly


So I have to read multiple CSV files, merge their headers(by removing duplicates) and put values in a final(merged) CSV file. I am trying to use SplFileObject for the first time. I started by reading a file. Below are details

file1.csv

"A","B","C","D
1,2,3,4

merge.csv

$file = new SplFileObject('file1.csv');
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
    print_r($row);
}

It outputs:

Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => D
1,2,3,4
)

Why it did not make another array for the next row?


Solution

  • try this, store your data in array and print it.

    $file = new SplFileObject('file1.csv');
    $file->setFlags(SplFileObject::READ_CSV);
    foreach ($file as $row) {
       $new_array[] = $row;
    }
    print_r($new_array);
    

    OUTPUT

    Array
    (
        [0] => A
        [1] => B
        [2] => C
        [3] => D
        [4] => 1
        [5] => 2
        [6] => 3
        [7] => 4
    )
    

    OR try this,

    $file = fopen('file1.csv', 'r');
    while (($line = fgetcsv($file)) !== FALSE) {
      //$line is an array of the csv elements
      print_r($line);
    }
    fclose($file);