Generate CSV from Array

function generateCsv($data, $delimiter = ',', $enclosure = '"') {
       $handle = fopen('php://temp', 'r+');
       foreach ($data as $line) {
               fputcsv($handle, $line, $delimiter, $enclosure);
       while (!feof($handle)) {
               $contents .= fread($handle, 8192);
       return $contents;


$data = array(
       array(1, 2, 4),
       array('test string', 'test, literal, comma', 'test literal "quotes"'),

echo generateCsv($data);
// outputs:
// 1,2,4
// "test string","test, literal, comma","test literal""quote"""


  1. User Avatar
    Permalink to comment#

    Ok this is a sweet function!

  2. User Avatar
    Jared Hocutt
    Permalink to comment#

    This is very helpful. I realize that this is an older post, but I wanted to point out that it appears that you haven’t declared the variable $contents prior to appending to it.

  3. User Avatar
    Mike Timmerman

    Awesome, thanks!

  4. User Avatar
    Permalink to comment#

    This is what they have now in php

  5. User Avatar
    Permalink to comment#

    This guy added a nice touch – array keys as header

    write out the headers

    fputcsv($fh, array_keys(current($data)));

  6. User Avatar
    Permalink to comment#

    Writing a file just to transform array to CSV is very resource heavy and slow. This is similar approach, but uses only memory:

Leave a Comment

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.