Thursday, 6 September 2018

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 PHPMySQL 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.

0 comments:

Post a Comment