使用PHPWord下载生成的文件

时间:2017-11-21 13:56:40

标签: php download phpword

我正在尝试使用PHPWord插件将某些HTML转换为.docx

但是当我下载文件时,我只会搞砸像这样的字符:  PK########�^uK�j�#c###!#######[Content_Types].xml���N�0#E�|E�-Jܲ@#5��#*Q>5'��_�8}�=��D#AC�v#)��s�G�G��5� "j�J6,#,#'��nQ���s~�2L�)a���m#�d|5�m#F�#K�L)�s�r V�#8�T>Z��5.x#�C,��

这是我的代码:

<?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');
?>

我已经在网上搜索过但不知道如何继续。

2 个答案:

答案 0 :(得分:1)

只需使用内置功能,如下所示

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

最后一个参数将强制下载生成的文件。

答案 1 :(得分:0)

attachement;filename="teste.docx"之间添加一个空格,以便标题为

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

并添加以下标题:

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

<强>更新

您可以尝试将文件保存到磁盘并从中发送,我也会遇到这样的问题并且它为我解决了:

$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);