Home / Use PHP’s fputcsv without writing to a file

Use PHP’s fputcsv without writing to a file

PHP’s fputcsv function is very useful for creating CSV files, but by default will write out to a file. There are a couple of tricks to be able to keep it all in memory or instead write the CSV data out directly to the web browser without having to write your own custom functions.

Array to CSV function using fputcsv

This function takes an array and returns the correctly formatted CSV data as a string using an in-memory buffer. It takes the same parameters as the fputcsv function, passing them through to it, so it can be used in the same way as fputcsv.

function array2csv($fields, $delimiter = ",", $enclosure = '"', $escape_char = "\")
{
    $buffer = fopen('php://temp', 'r+');
    fputcsv($buffer, $fields, $delimiter, $enclosure, $escape_char);
    rewind($buffer);
    $csv = fgets($buffer);
    fclose($buffer);
    return $csv;
}

Note that you can substitute php://temp for php://memory. The only difference between the two is that php://memory will always store its data in memory, whereas php://temp will use a temporary file once the amount of data stored hits a predefined limit (the default is 2 MB).

Here’s an example:

echo array2csv(array('apples', 'bananas', 'oranges', 'pears'));

And the output:

apples,bananas,oranges,pears

Writing the array straight out to the browser

Instead of buffering the CSV data in memory, you can write it directly out to the data by using php://output instead of php://temp or php://memory:

function array2csv($array)
{
    $output = fopen('php://output', 'w');
    fputcsv($output, $array);
    fclose($output);
}

Note that if you are writing CSV data directly out to the browser, you’ll want to set the appropriate headers too.