Search code examples
phparrayscsvfputcsv

Convert 2D Array to CSV file in PHP - String Error


I am trying to export a 2D array into a CSV file. This should be simple... but I tried every fputcsv example I could find and nothing works. Either the entire array is deposited into one row... Or when I try to insert via a foreach loop or I receive an error.

My code:

$test_array = explode(PHP_EOL, $array_data);

$fh = fopen('file.csv', 'w');

foreach($test_array as $line){
    fputcsv($fh, $line);
}

fclose($fh);

The error:

Warning: fputcsv() expects parameter 2 to be array, string given in /Users/pc_user/test_script.php on line 24

Contents of the array:

array(729) {
  [0]=>
  string(163) "Name;Title;Salary;FF;AD;HD;HE"
  [1]=>
  string(32) "Bob;Manager;Hidden;3.9;0.9;2.6;3"
  [2]=>
  string(32) "Tom;Student;Hidden;4.9;0.2;2.5;2"
  [3]=>
  string(34) "Jim;WorkerBee;Hidden;3.9;0.9;2.6;4"
  [4]=>
  string(35) "Fred;Poohbah;Hidden;3.5;0.4;3.6;2"
  [5]=>
  string(34) "Jake;Manager;Hidden;3.3;0.9;4.6;2"
  [6]=> ... And so on with 732 rows...

Solution

  • That happens because $line is a string and not an array. Since fputcsv expects second argument to be an array, change

    fputcsv($fh, $line);
    

    to

    fputcsv($fh, explode(';', $line));