问题描述
我的代码创建 Word 模板并在我运行 PHP 文件时立即下载。
如何创建一个按钮,当我点击它时允许我创建和下载 word 文件?
谢谢!
<?PHP
require_once 'vendor/autoload.PHP';
$PHPword = new \PHPOffice\PHPWord\PHPWord();
$ran = time();
$section = $PHPword->addSection();
$section->getStyle()
->setPaperSize('Letter')
->setLandscape()
;
$section->addText("Hello World!");
$file = 'test.docx';
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename="' . $file . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-transfer-encoding: binary');
header('Cache-Control: must-revalidate,post-check=0,pre-check=0');
header('Expires: 0');
$PHPword->save("PHP://output");
?>
解决方法
您可以对创建、保存单词并返回路径的 php 文件发出 curl 请求,然后使用 js 自动单击您设置了“href=”和路径的隐藏链接,然后具有属性“download=your_file_name”。
,Create a tmp folder the same directory youhave the code and add this
objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord,'Word2007');
$objWriter->save('tmp/helloWorld.docx');
$file = 'tmp/helloWorld.docx';
if (file_exists($file)) {`enter code here`
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}