安装phpword包
通过composer安装phpword包。因为是使用thinkphp架构,安装挺方便的。
直接下载phpword压缩包有问题。
composer require phpoffice/phpword
准备一个word模板(docx格式)
准备好word模板后,只需要用变量替换需要替换的值,如下图所示,将房东名替换成${name}。
前端调用代码
系统前端是使用vue3+element Ui开发的。所以请求用到axios。其中设置responseType
。responseType
表示服务器响应的数据类型,可以是 ‘arraybuffer’, ‘blob’, ‘document’, ‘json’, ‘text’, ‘stream’。默认的 responseType: ‘json’,
而axios下载文件需要设置responseType: ‘blob’,
PHP处理代码
后端方面的代码如下。Talk is cheap, show me the code.
one more thing
在传输过程中,可能会出现文件名是乱码的问题。也就是Content-Disposition中filename中文是乱码。解决方法如下:
php端使用json_encode(filename)
前端使用JSON.parse()
到此这篇关于php生成并下载word文件到本地实现方法详解的文章就介绍到这了