php 如何使用 CSV MIME 类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/398237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:36:45  来源:igfitidea点击:

How to use the CSV MIME-type?

phpcsvhttp-headersmime

提问by Sean Bright

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.

在我正在处理的 Web 应用程序中,用户可以单击指向 CSV 文件的链接。没有为 mime 类型设置标题,因此浏览器只是将其呈现为文本。我希望将此文件作为 .csv 文件发送,以便用户可以直接使用 calc、excel、gnumeric 等打开它。

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)

我的浏览器是 FF 3.0.1(在 linux 上)的夜间版本。它不工作的浏览器是 IE 7 和 FF 3.0(在 Windows 上)

Are there any quirks I am unaware of?

有什么我不知道的怪癖吗?

回答by Sean Bright

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.

这应该适用于大多数主要浏览器。

回答by gimel

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

您没有指定语言或框架,但以下标头用于文件下载:

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

回答by 4levels

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

使用 Internet Explorer,您通常必须指定 Pragma: 公共标头以及下载才能正常运行。

header('Pragma: public');

Just my 2 cents..

只有我的 2 美分..

回答by Yuri Korolov

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

此代码可用于导出任何文件,包括 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"');