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

Mor*_*rgs 5 php phpword

我正在使用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
Run Code Online (Sandbox Code Playgroud)

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

swi*_*ann 5

下面的示例可能有效,但是要在所有浏览器中获得预期的下载行为,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
Run Code Online (Sandbox Code Playgroud)

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

参考微软