【问题标题】:PHPWord Download Error (the office open XML file cannot be opened because there are problems with the contents)PHPWord 下载错误(office open XML 文件无法打开,因为内容有问题)
【发布时间】:2018-06-28 19:58:26
【问题描述】:

我的 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');


    ?>

【问题讨论】:

    标签: php xml phpword


    【解决方案1】:

    这对于 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;
    

    -谢谢

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      • 2011-04-21
      • 2016-10-07
      相关资源
      最近更新 更多