0

I am trying to write a .csv file with the following function that is described here:

Export to CSV via PHP

This is the function:

function array2csv(array &$array)
{
  if (count($array) == 0) {
    return null;
  }
  ob_start();
  $df = fopen('/path/to/file.csv', 'w');

  fputcsv($df, array_keys(reset($array)));
  foreach ($array as $row) {
    fputcsv($df, $row);
  }
  fclose($df);
  return ob_get_clean();
}

And I call it like so:

array2csv($array);

Where $array[0] (all other values follow this format) is as follows:

array(10) {
  [1]=>
  string(19) "2015-03-01 00:09:01"
  [2]=>
  string(11) "1234567890"
  [3]=>
  string(2) "26"
  [7]=>
  string(7) "0.10102"
  [8]=>
  string(12) "TESTING THIS"
  [9]=>
}

I have been battling for a while now trying to figure out why I get output as follows within the .csv file:

0,1,2,3,4,5,6,7,8,9
"2015-03-01 00:09:01",1234567890,26,0.10102,"TESTING THIS"
... etc ...

Have not really seen any other issues like this while doing research and I do not understand myself why this is happening.

Could anyone enlighten me as to what is going on here? Thank you!

Community
  • 1
  • 1
Craig van Tonder
  • 7,497
  • 18
  • 64
  • 109

2 Answers2

2

You are writing the keys to the file, here

fputcsv($df, array_keys(reset($array)));
Alex Andrei
  • 7,315
  • 3
  • 28
  • 42
  • Thanks Alex, appreciate the answer but i am going to give it to the other one because he was first and because he has expanded on the matter. – Craig van Tonder Aug 25 '15 at 19:33
2

It puts the array keys of your array as header in the first line:

fputcsv($df, array_keys(reset($array)));

Means you have a two dimensional array with 0-based keys, e.g.

Array ( 
    0 => Array ("2015-03-01 00:09:01",1234567890,26,0.10102,"TESTING THIS")
    1 => Array (...)
    2 => Array (...)
    3 => Array (...)
    4 => Array (...)
    5 => Array (...)
    6 => Array (...)
    7 => Array (...)
    8 => Array (...)
    9 => Array (...)
)
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • Thanks a heap. I really did not get what was going on there but I see now that I should have noticed that the values there are the same as the amount of values within the array, it's silly sometimes when you get stuck on one chain of thought :) – Craig van Tonder Aug 25 '15 at 19:34