php实现自动下载,使用PHPWord自动下载文件附件

这篇博客介绍了如何使用PHPWord库动态替换模板中的值,并将生成的文档保存为一个临时文件,然后通过HTTP头设置为附件下载,避免了`php://output`直接输出的问题。内容涉及文件保存、内容分发头设置以及临时文件的管理和删除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

php://output是一个只写流,写入您的屏幕(如echo)。

因此,

$document->save('php://output');不会将文件保存在服务器上的任何位置,它只会将其回显出来。

似乎,$document->save,不支持流封装,所以它从字面上做了一个名为"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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值