• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Sending a CSV file to the web browser with PHP

Sending a CSV file to the web browser with 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: text/csv');
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: text/csv');
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.

Check Out These Related posts:

  1. Change the email body character set with PEAR Mail_Mime
  2. Extracting attachments from an email message using PHP IMAP functions
  3. Extract Google Analytics report attachments with PHP
  4. Send CSV data to the browser from MySQL & PHP with fputcsv

Filed Under: PHP

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap