2015-11-23 52 views
4

我使用PHP Word & htmltodocx_converter創建一個Word文檔,所有工作都很好,但我只需要一個如何將文件發送到瀏覽器的示例無需將其保存在光盤上即可下載。我所有的例子中看到你的文件保存到光盤:PHP 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 

任何人都知道的我怎麼能輸出的文件在飛行中的瀏覽器?

+2

可能你可以通過在'PHP:// output'爲'filename' $,如果不只是創建一個正常的文件,創建正確的頭,它與'readfile'然後將其刪除讀取輸出與'unlink' – Steve

回答

4

下面的這個例子可能適用,但爲了在所有瀏覽器中獲得預期的下載行爲,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

+1

Word 2007的內容類型是'application/vnd.openxmlformats-officedocument.wordprocessingml.document' [(reference)](https://blogs.msdn.microsoft.com/vsofficedeveloper/2008/05/08/office-2007-file-format-mime-types-for-http-content-streaming-2 /) – jamsandwich

+0

@jamsandwich,謝謝 – swidmann

+0

請注意,文件擴展名也應該是.docx,對於Word 2007+文檔而不是.doc – jamsandwich

相關問題