Generating a CSV File using PHP

Written by James Mansson on May 17, 2013 Categories: PHP

A common feature to add to a web application is the ability to export data. For tabular data, a sensible format is often a CSV file. The one complication is the need to escape the data properly.

This task is pretty simple in PHP using its built-in functions. The first thing to do in the script generating the CSV is to set the appropriate headers, so the browser will recognise the response as being in CSV format. This can be done by something like:

header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=export.csv");
header("Pragma: no-cache");
header("Expires: 0");

In the above example, the file downloaded will be saved as export.csv. Naturally this can be set to something else, if that is more appropriate for the data.

The next task is to render the CSV file. We start by opening the output stream where we will write the rows of CSV:

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

We then loop through the data, writing each row with something like this:

fputcsv($fp, $cells);

The variable $cells should be an array of strings, representing the individual values within the row.

Finally, when we have finished writing the rows, we close the output stream:


The user should now receive a CSV file containing the data.

No Comments on Generating a CSV File using PHP

Leave a Reply

Your email address will not be published. Required fields are marked *