Symfony2 PHPWord 响应

Symfony2 PHPWord response

我正在尝试使用 PHPWord 包在 Symfony2 上生成一个 docx 文档。

在我的控制器中,我成功返回了一个docx文件,但是它是空的,我认为这是我错误的响应格式造成的。

public function indexAction($id)
{
    $PHPWord = new PHPWord();
    $section = $PHPWord->addSection();

    $section->addText(htmlspecialchars(
    '"Learn from yesterday, live for today, hope for tomorrow. '
        . 'The important thing is not to stop questioning." '
        . '(Albert Einstein)'
    ));


  // Saving the document
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');

return new Response($objWriter->save('helloWorld.docx'), 200, array('Content-Type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'));
}

PHPWord->save() returns 一个真值,所以这就是您的文件未被下载的原因。使用 return new Response(),您将响应的内容设置为 true(save 调用的结果),这就是您的响应为空的原因。

您有 2 个(可能还有更多我没有想到的)选项来生成和下载此文件..

1将文件保存到临时文件夹和服务器中

$filename = sprintf(
    '%s%sDoc-Storage%s%s.%s',
    sys_get_temp_dir(),
    DIRECTORY_SEPARATOR,
    DIRECTORY_SEPARATOR,
    uniqid(),
    'docx'
);

$objWriter->save($filename);

$response = new BinaryFileResponse($filename);

有关 BinaryFileResponse 的详细信息,请参阅 the docs

2忽略 Symfony 并直接通过 PHPWord 操作提供服务

$objWriter->save($filename, 'Word2007', true);
exit();

->save 方法提供了在内部下载生成的文件的所有操作(参见 the code),因此您需要做的就是将格式和第三个参数设置为 true,它将为您处理所有 headers。当然,它不会返回 Symfony 响应,但您将在遇到该异常之前退出。

非常感谢您的回答。

我是用第二种方法实现的,我认为是最好的。 我只需要 return 一个响应,否则文件已生成,但卡在 web 目录中。 使用此响应,一切正常,并出现下载提示,其中包含 "full" 文件。

这是我的代码:

$PHPWord = new PHPWord();

$section = $PHPWord->addSection();

$section->addText(htmlspecialchars(
            '"Learn from yesterday, live for today, hope for tomorrow. '
                . 'The important thing is not to stop questioning." '
                . '(Albert Einstein)'
        ));

    // Saving the document
    $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');     
    $filename="MyAwesomeFile.docx";
    $objWriter->save($filename, 'Word2007', true);

    $path = $this->get('kernel')->getRootDir(). "/../web/" . $filename;
    $content = file_get_contents($path);

    $response = new Response();
    $response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    $response->headers->set('Content-Disposition', 'attachment;filename="'.$filename);
    $response->setContent($content);
    return $response;

试试这个 class

<?php

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Settings;
use Symfony\Component\HttpFoundation\Response;

class WordResponse extends Response
{
    /**
     * WordResponse constructor.
     * @param string $name The name of the word file
     * @param PhpWord $word
     */
    public function __construct($name, &$word)
    {
        parent::__construct();

        // Set default zip library.
        if( !class_exists('ZipArchive')){
            Settings::setZipClass(Settings::PCLZIP);
        }

        $writer = IOFactory::createWriter($word, 'Word2007');

        //Set headers.
        $this->headers->set("Content-Disposition", 'attachment; filename="' . $name . '"');
        $this->headers->set("Content-Type", 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
        $this->headers->set("Content-Transfer-Encoding", 'binary');
        $this->headers->set("Cache-Control", 'must-revalidate, post-check=0, pre-check=0');
        $this->headers->set("Expires", '0');

        $this->sendHeaders();
        $writer->save('php://output');
    }
}

然后在你的控制器中执行:

return new WordResponse($phpWord, "filename.docx");