使用PHPWord自动下载文件附件 [英] Auto download the file attachment using PHPWord
问题描述
我正在尝试使用PHPWord生成Word文档.并且可以成功生成文档.但是存在一个问题,我生成的Word文档将保存在服务器上.如何使它可以立即下载?
I'm trying to use PHPWord to generate word documents. And the document can be generated successfully. But there is a problem where my generated word document will be saved on the server. How can I make it available to download straight away?
示例:
$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.
我如何链接到标题以如下方式下载它:
How can i link to the header to download it as follows:
header("Content-Disposition: attachment; filename='php://output'"); //not sure how to link this filename to the php://output..
请告知.
推荐答案
php://output
是只写流,它会写入屏幕(如echo
).
因此, $document->save('php://output');
不会将文件保存在服务器上的任何位置,只会将其回显.
So, $document->save('php://output');
will not save the file anywhere on the server, it will just echo it out.
似乎是$document->save
,它不支持流包装器,因此它实际上创建了一个名为"php://output"
的文件.尝试使用其他文件名(建议您使用临时文件,因为您只是想将其回显).
Seems, $document->save
, doesn't support stream wrappers, so it literally made a file called "php://output"
. Try using another file name (I suggest a temp file, as you just want to echo it out).
$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
$document->save($temp_file);
在header
中,filename
字段是PHP告诉浏览器文件的名称,它不必是服务器上文件的名称.这只是浏览器将其另存为的名称.
In the header
, the filename
field is what PHP tells the browser the file is named, it doesn't have to be a name of a file on the server. It's just the name the browser will save it as.
header("Content-Disposition: attachment; filename='myFile.docx'");
因此,将它们放在一起:
So, putting it all together:
$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
这篇关于使用PHPWord自动下载文件附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!