Creating a CSV file with PHP.

This a short tutorial on how to create a CSV file with PHP.

In this guide, we will also show you how to “force” the browser to download it as a file. This is extremely useful for creating “Export to CSV” buttons.

Take a look at the following PHP sample.

//The name of the CSV file that will be downloaded by the user.
$fileName = 'example.csv';

//Set the Content-Type and Content-Disposition headers.
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="' . $fileName . '"');

//A multi-dimensional array containing our CSV data.
$data = array(
    //Our header (optional).
    array("Name", "Registration Date"),
    //Our data
    array("Tom", "2012-01-04"),
    array("Lisa", "2011-09-29"),
    array("Harry", "2013-12-12")

//Open up a PHP output stream using the function fopen.
$fp = fopen('php://output', 'w');

//Loop through the array containing our CSV data.
foreach ($data as $row) {
    //fputcsv formats the array into a CSV format.
    //It then writes the result to our output stream.
    fputcsv($fp, $row);

//Close the file handle.

Here are the steps that we took.

  1. We gave our CSV file a name. This is the name that the file will have when the user downloads it.
  2. After that, we set our Content-Type and Content-Disposition headers. These headers will force the user’s browser to download the file.
  3. We then created a multidimensional array for our CSV data. This array should be an array that consists of arrays. Each array inside the $data array represents a row in our CSV file. The elements inside these arrays represents a column. If you look at the code above, you will see that we used a simple example of 4 rows and 2 columns. To understand this better, you can modify the array and change things around.
  4. After that, we opened up a PHP output stream.
  5. We then looped through the $data array. Inside the loop, we write each row to the output stream by using the function fputcsv.
  6. Finally, we closed the output stream.

If you run this PHP script on your server, you will see that a CSV file is automatically downloaded by the browser and that it contains the test data from our array.

See also: Reading a CSV file with PHP.