我正在尝试使用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.
Run Code Online (Sandbox Code Playgroud)
我如何链接到标题下载它如下:
header("Content-Disposition: attachment; filename='php://output'"); //not sure how to link this filename to the php://output..
Run Code Online (Sandbox Code Playgroud)
好心提醒.
Roc*_*mat 14
php://output是一个只写的流,写入您的屏幕(如echo).
因此,$document->save('php://output');不会将文件保存在服务器上的任何位置,它只会回显它.
似乎,$document->save不支持流包装器,所以它实际上是一个名为的文件"php://output".尝试使用另一个文件名(我建议一个临时文件,因为你只想回应它).
$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
$document->save($temp_file);
Run Code Online (Sandbox Code Playgroud)
在header,filename字段是PHP告诉浏览器文件被命名的字段,它不必是服务器上文件的名称.它只是浏览器将其保存为的名称.
header("Content-Disposition: attachment; filename='myFile.docx'");
Run Code Online (Sandbox Code Playgroud)
所以,把它们放在一起:
$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
Run Code Online (Sandbox Code Playgroud)
小智 8
$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;
Run Code Online (Sandbox Code Playgroud)
小智 5
这对我来说是工作:
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007', $download = true);
header("Content-Disposition: attachment; filename='File.docx'");
$objWriter->save("php://output");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27307 次 |
| 最近记录: |