Sending a CSV file to the web browser with PHP
Posted April 13th, 2009 in PHP
In the past I've written about how to save data as a CSV file using PHP, MySQL queries and mysqldump and in this post show how to send the results of this data to a web browser setting the headers correctly with PHP so the browser gives you a "save as" dialog instead of displaying it on the page. The headers also include the filename which is supplied as the default in the save as dialog.
The headers look like so, substituting filename.csv for the name you would like:
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="filename.csv"');
Then it's simply a matter of echo'ing out the CSV data to the web browser.
Compressing the data with ob_gzhandler
In order to cut down the amount of data actually transferred, it's a good idea to use PHP's ob_start() in combination with the gzhandler callback which will compress the output before sending it to the browser. The browser decompresses it and you still end up with a plain text file:
ob_start('ob_gzhandler');
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="filename.csv"');
Reading from a file
The CSV data will most likely come from a variable, from looping through data from a database or from a file. To echo the contents of the file to the browser do this:
readfile($filename);
where $filename is the filename of the file.
Related posts:
- Create a CSV file from MySQL with PHP (Sunday, April 12th 2009)
- Export data to CSV from MySQL (Wednesday, April 8th 2009)
- Set the content encoding type with PHP headers (Saturday, December 13th 2008)
- Image headers with PHP (Tuesday, July 22nd 2008)
- Using mysqldump to save data to CSV files (Saturday, December 15th 2007)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

