微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用PHPWord自动下载文件附件

我正在尝试使用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..

好心提醒.

解决方法:

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

所以,$document-> save(‘PHP:// output’);不会将文件保存在服务器上的任何位置,它只会将其回显.

似乎,$document-> save,不支持流包装器,因此它实际上创建了一个名为“PHP:// output”的文件.尝试使用另一个文件名(我建议一个临时文件,因为你只想回应它).

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

标题中,文件名字段是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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐