128

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?

Tadeck
  • 132,510
  • 28
  • 152
  • 198

5 Answers5

225

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.

chiborg
  • 26,978
  • 14
  • 97
  • 115
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
12

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

"Content-Disposition: attachment; filename=abc.csv"
gimel
  • 83,368
  • 10
  • 76
  • 104
5

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..

4levels
  • 3,134
  • 1
  • 23
  • 22
  • 5
    Pragma: public has no meaning whatsoever for Internet Explorer. (I worked on the component in question, and I grepped the source). – EricLaw Aug 12 '13 at 19:38
  • Possibly the actual utility of this is to replace a preexisting Pragma: no-cache header? – Doin Jan 15 '14 at 14:38
2

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"');
Bryan
  • 1,613
  • 16
  • 18
Yuri Korolov
  • 500
  • 2
  • 6
0

I tried to use text/csv but it did not work for me after that tried different stuff and I figured out that if we use this text/plain. Now the file upload is completed. as expected. This problem was in the Yii2 file upload widget.

Example response after success.

{"files":[{"name":"unit_ids list - Sheet1.csv","type":"text/plain","size":30,"base_url":"https://s3-eu-west-1.amazonaws.com/cdn.abc.co","path":"1/g2qVy3JtyZBLaRUd8c5gMOtSyrTEwdzR.csv","url":"https://s3-eu-west-1.amazonaws.com/cdn.abc.co/1/g2qVy3JtyZBLaRUd8c5gMOtSyrTEwdzR.csv","delete_url":"/coupons/default/sheet-delete?path=1%2Fg2qVy3JtyZBLaRUd8c5gMOtSyrTEwdzR.csv"}]}
Hassan Raza
  • 671
  • 10
  • 27