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.)
//NAME THE FILE $table = "test"; //BUILD CSV CONTENT $csv = '"Column 1","Column 2"' . "n"; //BUILD CSV ROWS $csv .= '"Column 1 Content","Column 2 Content"' . "n"; $csv .= '"Column 1 Content","Column 2 Content"' . "n"; $csv .= '"Column 1 Content","Column 2 Content"' . "n"; $csv .= '"Column 1 Content","Column 2 Content"' . "n"; $csv .= '"Column 1 Content","Column 2 Content"' . "n"; //OUPUT HEADERS header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename="$table.csv";" ); header("Content-Transfer-Encoding: binary"); //OUTPUT CSV CONTENT echo($csv);