Download produced file with PHPWord

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

I am trying to use the PHPWord plugin to convert some HTML into .docx

But when i download the file, I get only messed up charecters like:

Here is my code:

<?php error_reporting (E_ALL | E_STRICT); @ini_set ('display_errors', 'on'); require_once '../../../../vendor/autoload.php';  $my_content = $_POST['html_content'];  $phpWord = new \PhpOffice\PhpWord\PhpWord(); $section = $phpWord->addSection();  \PhpOffice\PhpWord\Shared\Html::addHtml($section, $my_content);  header('Content-Type: application/octet-stream'); header('Content-Disposition: attachement;filename="teste.docx"'); $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $objWriter->save('php://output'); ?> 

I already searched into the Web but got no clue how to proceed.

回答1:

just use the builtin functionality as follows

$phpWord->save('teste.docx', 'Word2007', true); 

The last parameter will force a download of the produced file.



回答2:

add a space between attachement; and filename="teste.docx" so the header will be

header('Content-Disposition: attachment; filename="teste.docx"'); 

and add the following header:

header('Content-Description: File Transfer'); 

Update

You can try saving the file to disk and sending from it, I also head problems like this and it solved for me:

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $objWriter->save($filePath);  header("Expires: Mon, 1 Apr 1974 05:00:00 GMT"); header("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT"); header("Cache-Control: no-cache, must-revalidate"); header("Pragma: no-cache"); header('Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document;'); header("Content-Disposition: attachment; filename=file.docx"); readfile($filePath); unlink($filePath); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!