Create a csv file to download using php

A common feature for website administrators is to get a backup or dump in csv format from the database.

Sometimes this feature is very specific and the PHP developer needs to write code that creates a csv file for download instead of relying on existing functions within the used framework.

A lot of examples on the internet show how to either loop over an array and format it line by line using implode, which, among other things, doesn’t handle data that contains commas that well.

Other examples tell the reader to use fputcsv() but that actually writes a file to a directory on the server, using the file handle you pass to it as an argument.

This is not a solution if you want to present your users with a file download dialog for the csv, not to mention the site’s host might not allow you to pick and choose which directory is writable.

However, user ‘MagicalTux at ooKoo dot org’ provided a simple solution in the comment section of the documentation for fputcsv() on php.net.



$out = fopen('php://output', 'w');

fputcsv($out, array('this','is some', 'csv "stuff", you know.'));

fclose($out);

Basically, you provide a filehandle to the output instead of an actual file, as simple as that.

Unfortunately this easy method seems to be less known, or at the least a lot less advertised as the “bad” methods.

This is my way of trying to put the word out that there is a better solution available.

Kudoos to “MagicalTux at ooKoo dot org”!