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.)
05 | $csv = '"Column 1","Column 2"' . "\n" ; |
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" ; |
15 | header( "Pragma: public" ); |
17 | header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" ); |
18 | header( "Cache-Control: private" ,false); |
19 | header( "Content-Type: application/octet-stream" ); |
20 | header( "Content-Disposition: attachment; filename=\"$table.csv\";" ); |
21 | header( "Content-Transfer-Encoding: binary" ); |
No comments:
Post a Comment