PHP Word,将生成的文件作为输出发送到浏览器,而不将其保存在光盘上


PHP Word, send generated file to browser as output without saving it on disc

我使用的是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

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

下面的例子可能有效,但为了在所有浏览器中获得预期的下载行为,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:Word2007的正确标题应该是application/vnd.openxmlformats-officedocument.wordprocessing‌​ml.document

参考Microsoft