How to use the CSV MIME-type?

PhpCsvHttp HeadersMime

Php Problem Overview


In a web application I am working on, the user can click on a link to a CSV file. There is no header set for the mime-type, so the browser just renders it as text. I would like for this file to be sent as a .csv file, so the user can directly open it with calc, excel, gnumeric, etc.

header('Content-Type: text/csv');
echo "cell 1, cell 2";

This code works as expected on my computer (Isn't that how it always is?) but does not work on another computer.

My browser is a nightly build of FF 3.0.1 (on linux). The browsers it did not work in were IE 7 and FF 3.0 (on windows)

Are there any quirks I am unaware of?

Php Solutions


Solution 1 - Php

You could try to force the browser to open a "Save As..." dialog by doing something like:

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyVerySpecial.csv');
echo "cell 1, cell 2";

Which should work across most major browsers.

Solution 2 - Php

You are not specifying a language or framework, but the following header is used for file downloads:

"Content-Disposition: attachment; filename=abc.csv"

Solution 3 - Php

With Internet Explorer you often have to specify the Pragma: public header as well for the download to function properly..

header('Pragma: public');

Just my 2 cents..

Solution 4 - Php

This code can be used to export any file, including csv

// application/octet-stream tells the browser not to try to interpret the file
header('Content-type: application/octet-stream');
header('Content-Length: ' . filesize($data));
header('Content-Disposition: attachment; filename="export.csv"');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiontheman_on_vistaView Question on Stackoverflow
Solution 1 - PhpSean BrightView Answer on Stackoverflow
Solution 2 - PhpgimelView Answer on Stackoverflow
Solution 3 - Php4levelsView Answer on Stackoverflow
Solution 4 - PhpYuri KorolovView Answer on Stackoverflow