Search the blog

fputcsv is invaluable for creating CSVs but it’s designed to work with files. What if you wish to output a CSV file to the output buffer? It’s actually quite easy as the commented code below shows.

// Your data, an array of arrays
$array = [

    ['Cell 1', 'Cell 2', 'Cell 3'],
    ['Cell 1', 'Cell 2', 'Cell 3']
    // ...
    
];

// Output to php://output, a write-only stream that goes to the output buffer
$stream = fopen('php://output', 'w');

// A CSV is done one line at a time
foreach ($data as $line) {

    // There should be no arrays or objects in $line
    fputcsv($stream, $line);

}

fclose($stream);
Tim Bennett is a Leeds-based web designer from Yorkshire. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.