PHPWord下载错误(办公室打开的XML文件无法打开,因为内容有问题)

时间:2018-01-19 14:35:56

标签: php xml phpword

我的PHPWord实现有问题。我正在构建一个功能,允许用户将内容下载到word并使用PHPWord。但是,在下载文档后,我在打开时遇到错误:

  由于内容存在问题,无法打开office open XML文件

我只能在接受恢复程序后预览word文件的内容,我认为这不是用户友好的。

这是我的PHP代码。

 <?php
    require_once '../assets/vendor/autoload.php';

        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $section = $phpWord->addSection();
        \PhpOffice\PhpWord\Shared\Html::addHtml($section, "Content");

        header('Content-Description: File Transfer'); 
        header("Content-Type: application/docx");
        header("Content-Transfer-Encoding: binary");
        header('Content-Disposition: attachment;filename="test.docx"');

        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $objWriter->save('test.docx');


    ?>

1 个答案:

答案 0 :(得分:0)

对于PHPWord,这是一个非常常见的问题。希望以下代码片段可以解决您的问题,因为它解决了我的问题。

$doc_filename = "Test_Report_". date("d-m-Y").".docx";

// Save file
// Saving the document as OOXML file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');

$temp_file_uri = tempnam('', 'anytext');
$objWriter->save($temp_file_uri);

//download code
header('Content-Description: File Transfer');
header("Content-Type: application/docx");//header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$doc_filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Content-Length: ' . filesize($temp_file_uri));
readfile($temp_file_uri);
unlink($temp_file_uri); // deletes the temporary file
exit;

-Thanks