使用PHPWord自动下载文件附件

bfnvny8b  于 2023-11-16  发布在  PHP
关注(0)|答案(8)|浏览(136)

我正在尝试使用PHPWord生成word文档。文档可以成功生成。但是我生成的word文档在服务器上保存时出现了问题。我如何使其可以立即下载?
样品名称:

$PHPWord = new PHPWord();
//Searching for values to replace
$document = $PHPWord->loadTemplate('doc/Temp1.docx');
$document->setValue('Name', $Name);
$document->setValue('No', $No);
$document->save('php://output'); //it auto save into my 'doc' directory.

字符串
我如何链接到标题下载它如下:

header("Content-Disposition: attachment; filename='php://output'"); //not sure how to link this filename to the php://output..


请指教。

piok6c0g

piok6c0g1#

php://output是一个只写的流,它会写入你的屏幕(像echo)。
因此,$document->save('php://output');不会将文件保存到服务器上的任何位置,它只是回显它。
看起来,$document->save不支持流 Package 器,所以它确实创建了一个名为"php://output"的文件。尝试使用其他文件名(我建议使用临时文件,因为你只想回显它)。

$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
$document->save($temp_file);

字符串
header中,filename字段是PHP告诉浏览器的文件名,它不一定是服务器上的文件名。它只是浏览器将其保存的名称。

header("Content-Disposition: attachment; filename='myFile.docx'");


所以,把它们放在一起:

$PHPWord = new PHPWord();
//Searching for values to replace
$document = $PHPWord->loadTemplate('doc/Temp1.docx');
$document->setValue('Name', $Name);
$document->setValue('No', $No);
// // save as a random file in temp file
$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
$document->save($temp_file);

// Your browser will name the file "myFile.docx"
// regardless of what it's named on the server 
header("Content-Disposition: attachment; filename='myFile.docx'");
readfile($temp_file); // or echo file_get_contents($temp_file);
unlink($temp_file);  // remove temp file

sgtfey8w

sgtfey8w2#

$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');

$filename = 'MyFile.docx';

$objWriter->save($filename);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
flush();
readfile($filename);
unlink($filename); // deletes the temporary file
exit;

字符串

ufj5ltwl

ufj5ltwl3#

这是我的工作:

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007', $download = true);

header("Content-Disposition: attachment; filename='File.docx'");

$objWriter->save("php://output");

字符串

gcxthw6b

gcxthw6b4#

现在版本为0.13.0 https://github.com/PHPOffice/PHPWord

<?
require_once "../include/PHPWord-develop/bootstrap.php";

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('template.docx');

$templateProcessor->setValue('var01', 'Sun');
$templateProcessor->setValue('var02', 'Mercury');

//#####################################################
// Save File
//#####################################################
//#####################################################
header("Content-Disposition: attachment; filename='output01.docx'");
  $templateProcessor->saveAs('php://output');
//#####################################################
//#####################################################
?>

字符串

enyaitl3

enyaitl35#

Laravel的一个简单的解决方案,基于@user3214824的答案。

// ...    
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
$doc_name = 'fileName.docx';
$objWriter->save($doc_name); // saving in the public path just for testing

return response()->download(public_path($doc_name))->deleteFileAfterSend(true);

字符串

7d7tgy0s

7d7tgy0s6#

抱歉,这是后来才出现的。我在试图解决同样的问题时偶然发现了这个问题。我能够在Laravel 5上使用下面的命令:

$file_dir = $template_upload_dir.DIRECTORY_SEPARATOR.'filename.docx';
    $tags = array();
    if (file_exists($file_dir)) {
        $templateProcessor = new TemplateProcessor($file_dir);
        $tags = $templateProcessor->getVariables();
        $replace = array(''); 

        $templateProcessor->setValue($tags, $replace);
        $save_file_name = $fullname.'-'.$inv_code.'-'.date('YmdHis').'.docx';
        $templateProcessor->saveAs($save_file_name);

        return response()->download($save_file_name)->deleteFileAfterSend(true);
    }

字符串
希望能帮到别人!!

1tuwyuhd

1tuwyuhd7#

// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
header("Content-Disposition: attachment; filename='myFile.docx'");
$objWriter->save("php://output");

字符串

zd287kbt

zd287kbt8#

我正在使用laravel 10.x和PHPWord 1.1。在尝试了多种解决方案后,我使用了基于@barryvdh的medium article的laravel StreamedResponse类来流式传输大型CSV,我修改了代码以使用PHPWord

$phpWordInstance = new PhpWord();
        //all your other code here
        $fileName = 'test.docx';

        $streamedResponse = new \Symfony\Component\HttpFoundation\StreamedResponse(callback : function () use ($phpWordInstance,$fileName) {
            $xmlWriter = IOFactory::createWriter($phpWordInstance, 'Word2007');
            $xmlWriter->save('php://output');
        },
            status: 200,
            headers: [
                'Content-Type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'Content-Disposition' => sprintf('attachment; filename="%s"',$fileName),
            ]);

        return $streamedResponse;

字符串
对于mimetype请参考What is a correct MIME type for .docx, .pptx, etc.?

相关问题