Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to convert array to csv ,im able to convert the associative array to csv.

But not able to get the headers.

I want the NUMBER TYPE DATE as headers dynamically

Below is the array i converrted .

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 given below .But not able to get the headers but its values are coming.

<?
 $fp1 = fopen('file.csv', 'w');

foreach ($arr2 as $fields) 
{
    fputcsv($fp1, $fields);
}

fclose($fp1);
?>
share|improve this question
2  
use array_keys function at the beginning to put in the headers. –  Jon May 3 at 20:09

1 Answer

up vote 4 down vote accepted

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

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

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


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

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

(Note that this assumes you have no blank rows -- a blank row would return array() which will issue a warning with the combine and put non-sense into data.)

share|improve this answer

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.