php 用于下载 Microsoft Word 和 Excel 文件的 http 标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11487365/
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-25 00:38:37  来源:igfitidea点击:

http header for downloading Microsoft Word and Excel files

phphtml

提问by JLearner

I can download my microsoft word successfully if I named it in the filename by default. But if I use $variables to name it. The document extension will be unknown.

如果我默认在文件名中命名它,我可以成功下载我的microsoft word。但是如果我使用 $variables 来命名它。文档扩展名将是未知的。

Sample:

样本:

$No = 1; 
$Name = 'John'; 
$Test = 'Science';

//Download header
$document->save($doc);
header('Content-Description: File Transfer');
header('Content-Type: application/msword');
header("Content-Disposition: attachment; filename='$No_$Name_$Test.docx");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($doc));
ob_clean();
flush();
readfile($doc);

So if i rename my filename as variables. The file download will be without the docx extension. Anyone can advise?

因此,如果我将文件名重命名为变量。文件下载将没有 docx 扩展名。任何人都可以建议?

Thanks

谢谢

采纳答案by P M

Change this

改变这个

header('Content-Type: application/msword');

to

header('Content-Type: application/octet-stream');

EDIT:

编辑:

And change

并改变

header("Content-Disposition: attachment; filename='$No_$Name_$Test.docx");

to

header("Content-Disposition: attachment; filename=\"{$No}_{$Name}_{$Test}.docx\"");

回答by Konstantin Smolyanin

Correct headers are

正确的标题是

for Excel (*.xlsx):

对于 Excel (*.xlsx):

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $fileName . '"');

for Word (*.docx):

对于 Word (*.docx):

header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment;filename="' . $fileName . '"');

回答by David Valdivieso

The correct use of that header is:

该标头的正确使用是:

Content-Disposition: attachment; filename="fname.ext"note that if the name contains spaces it must be quoted

Content-Disposition: attachment; filename="fname.ext"请注意,如果名称包含空格,则必须用引号引起来

See RFC6266section 5. Examples

请参阅RFC6266第 5 节。 示例