Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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...
share|improve this question
    
$line is really not an array. You should explode every line on ; –  u_mulder Aug 3 '14 at 9:06
    
yes that worked. thanks. –  nodoze Aug 3 '14 at 9:17

1 Answer 1

up vote 1 down vote accepted

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));
share|improve this answer
1  
thank you havelock –  nodoze Aug 3 '14 at 9:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.