Sending a CSV file to the web browser with PHP

0 Shares
0
0
0

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.