Php array for csv conversion with column headers

I want to convert an array to csv, im to convert an associative array to csv.

But you canโ€™t get the headers.

I want DUMBER DYPE DATE to be dynamically displayed

Below is the array i converted.

Array ( [0] => Array ( [NUMBER] => 67 [TYPE] => Other [DATE] => 3/31/2011 ) [1] => Array ( [NUMBER] => 87 [TYPE] => something [DATE] => 3/28/2011 ) [2] => Array ( [NUMBER] => 67 [TYPE] => Other [DATE] => 3/2/2011 ) ) 

The code is below. But you canโ€™t get the headers, but its values โ€‹โ€‹are approaching.

 <? $fp1 = fopen('file.csv', 'w'); foreach ($arr2 as $fields) { fputcsv($fp1, $fields); } fclose($fp1); ?> 
+8
php
source share
4 answers

Just use array_keys to get the keys and write them to a file first.

 fputcsv($han, array_keys($arr[0])); foreach ($arr as $a) { ... } 

This assumes you have a numerical array (and it assumes that it is not empty). If arr[0] not guaranteed to be set, you can use array_shift or array_slice to extract the first element. (Or you can only have a flag in your loop of whether the title is already written - just the default value is false. If it is not, set it to true and print the title.)


While I'm in, you can use array_combine to go in the opposite direction (CSV to an array of associative arrays).

 $data = array(); $header = fgetcsv($han); while (($row = fgetcsv($han)) !== false) { $data[] = array_combine($header, $row); } 

(Note that this assumes that you do not have empty lines - an empty line will return array() , which will issue a warning in the combine and put insensitivity in data .)

+14
source share

DarrenK's answer is readable but incomplete. So, for noefites.

  $pathToGenerate = 'array.csv'; // your path and file name $header=null; $createFile = fopen($pathToGenerate,"w+"); foreach ($array as $row) { if(!$header) { fputcsv($createFile,array_keys($row)); fputcsv($createFile, $row); // do the first row of data too $header = true; } else { fputcsv($createFile, $row); } } fclose($createFile) 
+6
source share

Robert Clark's answer is very close, but requires simplification: there is no need for else :

  $pathToGenerate='array.csv'; // your path and file name $header=FALSE; $createFile=fopen($pathToGenerate,'w+'); foreach ($array as $row) { if (!$header) { fputcsv($createFile,array_keys($row)); $header=TRUE; } fputcsv($createFile,$row); // write the data for all rows } fclose($createFile); 
0
source share

This worked for me. Null $ header will not be null after assigning the keys, after which the lines will follow.

 $header=null; $createFile = fopen($pathToGenerate,"w+"); foreach ($assocArray as $row) { if(!$header){ fputcsv($createFile,array_keys($row)); }else{ fputcsv($createFile, $row); } } fclose($createFile); 

not as short as above, but I find it quite readable.

-one
source share

All Articles