使用PHP,强制浏览器下载Word Doc

时间:2015-10-29 03:41:19

标签: php html

为了解决下载动态生成的Word文档的问题,我一直在撞墙。我想有一个解决方案,点击按钮,它会要求用户下载word文档。我能够生成单词文档,但它已保存在我的本地目录中,而不是要求下载特定位置。在那之后,我做了一些更改但是它停止生成word文档。我不确定我做错了什么。 有人可以让我知道我做错了什么。

<?
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
require_once($_SERVER['DOCUMENT_ROOT'].'/vendor/phpoffice/src/PhpWord/Autoloader.php');

\PhpOffice\PhpWord\Autoloader::register();
$phpWord = new \PhpOffice\PhpWord\PhpWord();
if(isset($_POST['postData'])){
$jsonData = json_decode($_POST['postData'],true);
$fieldText = $jsonData['testingTime'];
$section = $phpWord->addSection();
$header = $section->addHeader();
$section->addText($fieldText);
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord,'Word2007');
//$filename  = "Result.docx"; #Also, this is not working
$objWriter->save('Result.docx');
header('Content-Description: File Transfer');
//header('Content-Type: application/force-download');
header('Content-type: application/octet-stream');
header("Content-Disposition: attachment; Filename=Result.docx");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');
header('Content-Length: ' .filesize('Result.docx'));
flush();
readfile('Result.docx');
unlink('Result.docx'); // deletes the temporary file
exit;}
?>

0 个答案:

没有答案