要给最常用出租屋管理系统增加个合同功能,mark下知识点。要生成合同就需要使用phpword。文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
安装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’,
axios.post(url, data, { headers: { 'X-CSRF-TOKEN': this.token }, responseType: 'blob' })
.then((res) => {
const { data, headers } = res
const contentDisposition = headers['content-disposition']
const patt = new RegExp('filename=([^;]+\.[^\.;]+);*')
const result = patt.exec(contentDisposition)
const filename = decodeURI(JSON.parse(result[1])) // 处理文件名,解决中文乱码问题
const blob = new Blob([data], { type: headers['content-type'] })
let dom = document.createElement('a')
let url = window.URL.createObjectURL(blob)
dom.href = url
dom.download = decodeURI(filename)
dom.style.display = 'none'
document.body.appendChild(dom)
dom.click()
dom.parentNode.removeChild(dom)
window.URL.revokeObjectURL(url)
}).catch((err) => { })
PHP处理代码
后端方面的代码如下。Talk is cheap, show me the code.
public function contract()
{
$tmp=new \PhpOffice\PhpWord\TemplateProcessor('static/wordfile/contract.docx');//打开模板
$tmp->setValue('name', '君常笑');//替换变量name
$tmp->setValue('mobile', '12');//替换变量mobile
$tmp->saveAs('../tempfile/简历.docx');//另存为
$file_url = '../tempfile/简历.docx';
$file_name=basename($file_url);
$file_type=explode('.', $file_url);
$file_type=$file_type[count($file_type)-1];
$file_type=fopen($file_url, 'r'); //打开文件
//输入文件标签
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: ".filesize($file_url));
header("Content-Disposition:attchment; filename=" . json_encode('合同.docx'));
//输出文件内容
echo fread($file_type, filesize($file_url));
fclose($file_type);
}
one more thing
在传输过程中,可能会出现文件名是乱码的问题。也就是Content-Disposition中filename中文是乱码。解决方法如下:
php端使用json_encode(filename)
前端使用JSON.parse()
到此这篇关于php生成并下载word文件到本地实现方法详解的文章就介绍到这了,更多相关php下载word文件内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:php生成并下载word文件到本地实现方法详解


基础教程推荐
- PHP数据加密方式梳理介绍 2023-07-03
- thinkPHP3.2.2框架行为扩展及demo示例 2022-11-07
- PHP删除数组中指定值的元素常用方法实例分析【4种方法】 2022-11-12
- TP5 连接多个数据库及使用方法 2023-08-30
- PHP实现创建一个RPC服务操作示例 2023-04-01
- PHP使用SMTP邮件服务器发送邮件示例 2022-11-16
- TP5(thinkPHP5框架)基于bootstrap实现的单图上传插件用法示例 2023-01-19
- PHP实现生成数据字典功能示例 2022-10-18
- php中使用array_filter()函数过滤数组实例讲解 2023-05-19
- laravel model模型定义实现开启自动管理时间created_at,updated_at 2023-03-02