12

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);
?>
1
  • 3
    use array_keys function at the beginning to put in the headers. Commented May 3, 2013 at 20:09

4 Answers 4

21

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Your csv to array code will fail if one of the data rows is not the same length as the header.
10

DarrenK 's answer is readable but incomplete. So for the noephytes.

    $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)

Comments

2

Robert Clark's answer is very close, but still needs simplification: There's no need for the else clause:

    $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);

Comments

-2

This worked nicely for me null $header will not be null once you assign the keys then the rows 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.

1 Comment

This doesn't write the first row of the data to the file, only the header. It also doesn't change the value of $header so the headers will be repeated for every row of data, never writing any actual data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.