【问题标题】:How to create docx file and download it using PhpWord如何创建 docx 文件并使用 PhpWord 下载它
【发布时间】:2021-12-02 00:15:03
【问题描述】:

您好,我在尝试创建 docx 文件时总是出错,我想直接下载它。我的浏览器卡在ERR_INVALID_RESPONSE。顺便说一句,我正在使用 CodeIgniter 框架。这是代码。

<?php
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Writer\Word2007;

class Test extends MY_Controller{
   public function create()
   {
      $phpWord = new PhpWord();
      $section = $phpWord->addSection();
      $section->addText('Hello World!');
      $file = 'HelloWorld.docx';
      header("Content-Description: File Transfer");
      header('Content-Disposition: attachment; filename="' . $file . '"');
      header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
      header('Content-Transfer-Encoding: binary');
      header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
      header('Expires: 0');
      $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
      $xmlWriter->save("php://output");
   }
}

此代码仅取自 PhpWord 文档中的示例,但不知何故它不起作用。浏览器上的ERR_INVALID_RESPONSE 没有错误。我错过了什么?

【问题讨论】:

    标签: codeigniter-3 phpword


    【解决方案1】:

    经过几个小时的挖掘,我终于找到了解决问题的方法。存在问题是因为它与临时文件夹有关。所以我要做的是 1. 设置文件临时保存的路径和 2. 我必须告诉 Phpword 它应该使用该路径来存储生成的文件。

    $path = './uploads/tmp'; // Set the temporary path
    
    \PhpOffice\PhpWord\Settings::setTempDir($path); // Tell Phpword where the temporary path is
    

    这是完整的代码

    <?php
    use PhpOffice\PhpWord\PhpWord;
    use PhpOffice\PhpWord\Writer\Word2007;
    
    class Test extends MY_Controller{
       public function create()
       {
          $phpWord = new PhpWord();
          $section = $phpWord->addSection();
          $section->addText('Hello World!');
    
          $path = './uploads/tmp'; // Set the temporary path
          \PhpOffice\PhpWord\Settings::setTempDir($path); // Tell Phpword where the temporary path is
    
          $file = 'HelloWorld.docx';
          header("Content-Description: File Transfer");
          header('Content-Disposition: attachment; filename="' . $file . '"');
          header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
          header('Content-Transfer-Encoding: binary');
          header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
          header('Expires: 0');
          $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
          $xmlWriter->save("php://output");
       }
    }
    

    希望对遇到同样问题的人有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-07
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多