亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

安裝phpword包

通過composer安裝phpword包。因為是使用thinkphp架構(gòu),安裝挺方便的。

直接下載phpword壓縮包有問題。

composer require phpoffice/phpword

準備一個word模板(docx格式)

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

前端調(diào)用代碼

系統(tǒng)前端是使用vue3+element Ui開發(fā)的。所以請求用到axios。其中設(shè)置responseType。responseType 表示服務器響應的數(shù)據(jù)類型,可以是 ‘arraybuffer’, ‘blob’, ‘document’, ‘json’, ‘text’, ‘stream’。默認的 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])) // 處理文件名,解決中文亂碼問題
      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'));
        //輸出文件內(nèi)容
        echo fread($file_type, filesize($file_url));
        fclose($file_type);
    }

one more thing

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

php端使用json_encode(filename)

前端使用JSON.parse()

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

相關(guān)文章

最新評論