温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php怎么生成并下载word文件到本地

发布时间:2022-08-30 09:29:49 来源:亿速云 阅读:124 作者:iii 栏目:开发技术

这篇“php怎么生成并下载word文件到本地”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“php怎么生成并下载word文件到本地”文章吧。

安装phpword包

通过composer安装phpword包。因为是使用thinkphp架构,安装挺方便的。

直接下载phpword压缩包有问题。

composer require phpoffice/phpword

准备一个word模板(docx格式)

准备好word模板后,只需要用变量替换需要替换的值,如下图所示,将房东名替换成${name}。

php怎么生成并下载word文件到本地

前端调用代码

系统前端是使用vue3+element Ui开发的。所以请求用到axios。其中设置responseTyperesponseType 表示服务器响应的数据类型,可以是 ‘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文件到本地”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI