Generate a CSV file using PHP
by matt on February 28, 2006Q: How do you create a CSV file dynamically with PHP? I have tried many of the examples on the web but while the save/open prompt does show, it lets me know my file is unable to be opened. I need this to not be a file that is stored on my server but instead created at the time of demand.
A: The key to generating a CSV file using PHP that will be sent to your users web browser for them to open and do with as they want is to make sure you tell the browser that it is coming. Normally using PHP you just send the browser an html document and that is what the browser expects.
You need to tell the web browser to expect a file. In order to do this you have to use the header() functions built into PHP.
header(’Expires: 0′);
header(’Cache-control: private’);
header(’Cache-Control: must-revalidate, post-check=0, pre-check=0′);
header(’Content-Description: File Transfer’);
header(’Content-Type: application/vnd.ms-excel’);
header(’Content-disposition: attachment; filename=”file_name.xls”‘);
Then you just echo your data. You have to make sure not to send any information before you call your header functions or else you will get errors on your page and the file will not be downloadable but will be displayed in the browser.
