【问题标题】:PHP Word, send generated file to browser as output without saving it on discPHP Word,将生成的文件作为输出发送到浏览器而不将其保存在光盘上
【发布时间】:2016-02-25 15:47:29
【问题描述】:

我正在使用 PHP Word 和 htmltodocx_converter 创建一个 word 文档,一切正常,但我只需要一个示例,说明如何将文件发送到浏览器进行下载而不将其保存在光盘上。我看到的所有示例都将文件保存到您的光盘:

// Save File
$h2d_file_uri = tempnam( "", "htd" );
$objWriter = PHPWord_IOFactory::createWriter( $phpword_object, "Word2007" );
$objWriter->save( $filename ); // At this line, I would like to output the file to the browser

有人知道我如何将文件即时输出到浏览器吗?

【问题讨论】:

  • 可能你可以传入php://output作为$filename,如果不只是创建一个普通文件,创建正确的标题,用readfile读取它输出然后用unlink删除它

标签: php phpword


【解决方案1】:

以下示例可能有效,但要在所有浏览器中获得预期的下载行为,Content-Type 标头对于 Word2007 必须正确。也许您需要一些额外的标题才能正确输出。

你可以试试这个:

$filename = "YOUR_Filename.docx";
header( "Content-Type: application/vnd.openxmlformats-officedocument.wordprocessing‌​ml.document" );// you should look for the real header that you need if it's not Word 2007!!!
header( 'Content-Disposition: attachment; filename='.$filename );

$h2d_file_uri = tempnam( "", "htd" );
$objWriter = PHPWord_IOFactory::createWriter( $phpword_object, "Word2007" );
$objWriter->save( "php://output" );// this would output it like echo, but in combination with header: it will be sent

感谢@jamsandwich:Word 2007 的正确标题应该是application/vnd.openxmlformats-officedocument.wordprocessing‌​ml.document

Reference Microsoft

【讨论】:

  • Word 2007 的内容类型是application/vnd.openxmlformats-officedocument.wordprocessingml.document (reference)
  • 请注意,对于 Word 2007+ 文档,文件扩展名也应该是 .docx,而不是 .doc
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-30
  • 1970-01-01
  • 1970-01-01
  • 2015-12-14
  • 2018-01-09
相关资源
最近更新 更多