简体   繁体   English

PHPWord下载错误(由于内容存在问题,无法打开Office Open XML文件)

[英]PHPWord Download Error (the office open XML file cannot be opened because there are problems with the contents)

I am having a problem with my PHPWord implementation. 我的PHPWord实现存在问题。 I am building a feature that will allow users to download content to word and am using PHPWord for this. 我正在构建一项功能,该功能将允许用户将内容下载到word并为此使用PHPWord。 However, after the document is downloaded I am getting an error while opening: 但是,下载文档后,打开时出现错误:

the office open XML file cannot be opened because there are problems with the contents 由于内容存在问题,因此无法打开Office Open XML文件

I'm only able to preview the contents of the word file after the accepting the recovery procedure, which I think is not something user friendly. 在接受恢复过程后,我只能预览word文件的内容,我认为这不是用户友好的操作。

Here is my PHP code. 这是我的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');


    ?>

This is a very common issue for PHPWord.Hope the following code fragment will solve your problem as it solves mine. 这对于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 -谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM