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. timani
    Permalink to comment#

    Ok this is a sweet function!

  2. 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. Mike Timmerman

    Awesome, thanks!

  4. chestozo
    Permalink to comment#

    This is what they have now in php

  5. Bill
    Permalink to comment#

    This guy added a nice touch – array keys as header

    write out the headers

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

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

We have a pretty good* newsletter.