2014-11-06 50 views
2

我使用PHPWord在php中下載docx文件。但是如果我嘗試下載它,文件中沒有任何內容會打印出來。但內容會顯示在保存在服務器上的文件中。以下是我用過的代碼。任何人都可以告訴我問題是什麼。使用PHPWord不會打印在文檔中

<?php 
include "../includes/config.inc.php"; 
include '../PHPWord.php'; 

// Create a new PHPWord Object 
$PHPWord = new PHPWord(); 

// Every element you want to append to the word document is placed in a section. So you need a section: 
$section = $PHPWord->createSection(); 

$section->addText('CANDIDATES DETAILS'); 

$filename='test'; 

$file=$filename.'.docx'; 
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007'); 
$objWriter->save('/form_doc/'.$filename.'.docx'); 


//download the file 
header('Content-Description: File Transfer'); 
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); 
header('Content-Disposition: attachment; filename='.$file); 
header('Content-Transfer-Encoding: binary'); 
header('Expires: 0'); 
header('Cache-Control: must-revalidate'); 
header('Pragma: public'); 
header('Content-Length: ' . filesize($file)); 
readfile($file); 

在此先感謝。

問候,

NEHA

+1

的**頭之前**,你應該檢查'如果(file_exists( $ file)){// your code}',如果找不到,那麼這將是你的**文件路徑**問題。並記住'header'需要**完整文檔路徑** – 2014-11-06 06:40:17

+0

非常感謝你 – 2014-11-06 12:55:10

+0

嗯..你的歡迎 – 2014-11-06 13:40:03

回答

1

你應該設置路徑提交到readfile()filesize()功能:

$file = $filename.'.docx'; 
$filepath = '/form_doc/' . $file; 
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007'); 
$objWriter->save($filepath); 

//download the file 
header('Content-Description: File Transfer'); 
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); 
header('Content-Disposition: attachment; filename='.$file); 
header('Content-Transfer-Encoding: binary'); 
header('Expires: 0'); 
header('Cache-Control: must-revalidate'); 
header('Pragma: public'); 
header('Content-Length: ' . filesize($filepath)); 
readfile($filepath);