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

PHP Word,将生成的文件作为输出发送到浏览器,而不将其保存在光盘上,php,phpword,Php,Phpword,我正在使用PHP Word和htmltodocx_转换器创建Word文档,所有这些都可以正常工作,但我只需要一个示例,说明如何将文件发送到浏览器进行下载,而不将其保存在光盘上。我看到您将文件保存到光盘的所有示例: // Save File $h2d_file_uri = tempnam( "", "htd" ); $objWriter = PHPWord_IOFactory::createWriter( $phpword_object, "Word2007" ); $objWriter->

我正在使用PHP Word和htmltodocx_转换器创建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

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

下面的示例可能有效,但要在所有浏览器中获得预期的下载行为,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
感谢@jams三明治:Word 2007的正确标题应该是
application/vnd.openxmlformats-officedocument.wordprocessing‌​ml.document


您可以传入
php://output
作为
$filename
,如果不只是创建普通文件,请创建正确的标题,读取它以使用
readfile
输出,然后使用
unlink
删除它Word 2007的内容类型是
application/vnd.openxmlformats of cedocument.wordprocessingml.document
注意,对于Word 2007+文档,文件扩展名也应该是.docx,而不是.doc