blog-banner

Creating Downloadable CSV Files in PHP

  • CSV
  • Drupal 7
  • Drupal Planet

CSV Files in PHP

This blog explains, how to create a CSV file using PHP and how to download the file instead of displaying it.

<?php
  // Creates a new csv file and store it in tmp directory
  $new_csv = fopen('/tmp/report.csv', 'w');
  fputcsv($new_csv, $row);
  fclose($new_csv);

  // output headers so that the file is downloaded rather than displayed
  header("Content-type: text/csv");
  header("Content-disposition: attachment; filename = report.csv");
  readfile("/tmp/report.csv");
?>

This code tells the browser that it is generating a CSV file that should be offered for download, rather than displayed in the browser.

header("Content-type: text/csv");

The MIME type of content is text/csv, the official MIME type for CSV files.

header("Content-disposition: attachment; filename=report.csv");

header to supply a recommended filename and force the browser to display the save dialog.

readfile("/tmp/report.csv");

readfile — Outputs a file.

 

Get awesome tech content in your inbox