php生成并下載word文件到本地實現(xiàn)方法詳解
安裝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)文章
WordPress開發(fā)中用于獲取近期文章的PHP函數(shù)使用解析
這篇文章主要介紹了WordPress開發(fā)中用于獲取近期文章的PHP函數(shù)使用解析,即對wp_get_recent_posts函數(shù)的使用方法介紹,需要的朋友可以參考下2016-01-01php中通過Ajax如何實現(xiàn)異步文件上傳的代碼實例
php結(jié)合Ajax技術(shù)如何實現(xiàn)異步文件上傳 有了file filereader 對象的支持,異步文件上傳將變得簡單。(以前都會把form提交到iframe來實現(xiàn))2011-05-05PHP基于關(guān)聯(lián)數(shù)組20行代碼搞定約瑟夫問題示例
這篇文章主要介紹了PHP基于關(guān)聯(lián)數(shù)組20行代碼搞定約瑟夫問題,結(jié)合具體實例分析了php使用關(guān)聯(lián)數(shù)組解決約瑟夫問題的相關(guān)操作技巧,需要的朋友可以參考下2017-11-11