Friday, December 06, 2013

Proper PHP Headers for CSV Documents (All Browsers) | Zipline Interactive

Proper PHP Headers for CSV Documents (All Browsers) | Zipline Interactive

CSV or comma separated variable files are a common way of storing and transferring data from web applications or databases. These handy files can easily be opened as a spreadsheet in common editing programs like Microsoft Excel, Apple Numbers, or Open Office Calc.
Most developers have no problem generating a CSV document but many have had problems determining the proper headers to send prior to outputting the content of a PHP variable containing CSV information. Many articles have been written on the topic but very few if any contain headers that work in all browsers in including Internet Explorer 6-9 (IE 6,7,8, and 9). Many of the header combinations available online will work in Firefox and Safari but will fail when trying to force download of a CSV in Internet Explorer.
The following CSV document header code example has been tested and works in all major browsers. When run, it will generate a CSV file using PHP, store it in a variable called CSV, then echo the contents of the CSV to the browser.
(Note: For this to work properly this needs to be the only output created by the page. Your browser will see this output as a document and not standard HTML. Any other information on the page will cause the CSV to break or will result in header errors.)
01//NAME THE FILE
02$table "test";
03 
04//BUILD CSV CONTENT
05$csv '"Column 1","Column 2"' "\n";
06 
07//BUILD CSV ROWS
08$csv .= '"Column 1 Content","Column 2 Content"' "\n";
09$csv .= '"Column 1 Content","Column 2 Content"' "\n";
10$csv .= '"Column 1 Content","Column 2 Content"' "\n";
11$csv .= '"Column 1 Content","Column 2 Content"' "\n";
12$csv .= '"Column 1 Content","Column 2 Content"' "\n";
13 
14//OUPUT HEADERS
15header("Pragma: public");
16header("Expires: 0");
17header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
18header("Cache-Control: private",false);
19header("Content-Type: application/octet-stream");
20header("Content-Disposition: attachment; filename=\"$table.csv\";" );
21header("Content-Transfer-Encoding: binary");
22 
23//OUTPUT CSV CONTENT
24echo($csv);                    

No comments: