欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php生成并下載word文件到本地實(shí)現(xiàn)方法詳解

 更新時(shí)間:2022年08月29日 16:47:48   作者:最常用  
要給最常用出租屋管理系統(tǒng)增加個(gè)合同功能,mark下知識(shí)點(diǎn)。要生成合同就需要使用phpword。文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

安裝phpword包

通過(guò)composer安裝phpword包。因?yàn)槭鞘褂胻hinkphp架構(gòu),安裝挺方便的。

直接下載phpword壓縮包有問(wèn)題。

composer require phpoffice/phpword

準(zhǔn)備一個(gè)word模板(docx格式)

準(zhǔn)備好word模板后,只需要用變量替換需要替換的值,如下圖所示,將房東名替換成${name}。

前端調(diào)用代碼

系統(tǒng)前端是使用vue3+element Ui開(kāi)發(fā)的。所以請(qǐng)求用到axios。其中設(shè)置responseType。responseType 表示服務(wù)器響應(yīng)的數(shù)據(jù)類型,可以是 ‘arraybuffer’, ‘blob’, ‘document’, ‘json’, ‘text’, ‘stream’。默認(rèn)的 responseType: ‘json’,

而axios下載文件需要設(shè)置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])) // 處理文件名,解決中文亂碼問(wèn)題
      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');//打開(kāi)模板
        $tmp->setValue('name', '君常笑');//替換變量name
        $tmp->setValue('mobile', '12');//替換變量mobile
        $tmp->saveAs('../tempfile/簡(jiǎn)歷.docx');//另存為
        $file_url = '../tempfile/簡(jiǎn)歷.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'); //打開(kāi)文件
        //輸入文件標(biāo)簽
        header("Content-type: application/octet-stream");
        header("Accept-Ranges: bytes");
        header("Accept-Length: ".filesize($file_url));
        header("Content-Disposition:attchment; filename=" . json_encode('合同.docx'));
        //輸出文件內(nèi)容
        echo fread($file_type, filesize($file_url));
        fclose($file_type);
    }

one more thing

在傳輸過(guò)程中,可能會(huì)出現(xiàn)文件名是亂碼的問(wèn)題。也就是Content-Disposition中filename中文是亂碼。解決方法如下:

php端使用json_encode(filename)

前端使用JSON.parse()

到此這篇關(guān)于php生成并下載word文件到本地實(shí)現(xiàn)方法詳解的文章就介紹到這了,更多相關(guān)php下載word文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論