PHP完美生成word文檔,可加入html元素

PHP生成word文檔,網(wǎng)上有很多方法,有調(diào)用COM組件生成的,有安裝PHP擴(kuò)展生成的,也有引用第三方類庫(kù),如phpword生成的。以下為最簡(jiǎn)潔的兩種方法,無(wú)須安裝其他,只要你安裝了php環(huán)境便可以直接生成。

<?php

header("Content-type:text/html;charset=utf-8");

/**
 * @desc 方法一、生成word文檔
 * @param $content
 * @param string $fileName
 */
function createWord($content='',$fileName='new_file.doc'){
    if(empty($content)){
        return;
    }
    $content='<html 
            xmlns:o="urn:schemas-microsoft-com:office:office" 
            xmlns:w="urn:schemas-microsoft-com:office:word" 
            xmlns="http://www.w3.org/TR/REC-html40">
            <meta charset="UTF-8" />'.$content.'</html>';
    if(empty($fileName)){
        $fileName=date('YmdHis').'.doc';
    }
    $fp=fopen($fileName,'wb');
    fwrite($fp,$content);
    fclose($fp);
}

$str = '<h1 style="color:red;">我是h1</h1><h2>我是h2</h2>';
createWord($str);


/**
 * @desc 方法二、生成word文檔并下載
 * @param $content
 * @param string $fileName
 */
function downloadWord($content, $fileName='new_file.doc'){

    if(empty($content)){
        return;
    }

    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=$fileName");

    $html = '<html xmlns:v="urn:schemas-microsoft-com:vml"
         xmlns:o="urn:schemas-microsoft-com:office:office"
         xmlns:w="urn:schemas-microsoft-com:office:word" 
         xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" 
         xmlns="http://www.w3.org/TR/REC-html40">';
    $html .= '<head><meta charset="UTF-8" /></head>';

    echo $html . '<body>'.$content .'</body></html>';

}

$str = '<h4>表頭:</h4>
<table border="1">
<tr>
  <th>姓名</th>
  <th>電話</th>
  <th>電話</th>
</tr>
<tr>
  <td>Bill Gates</td>
  <td>555 77 854</td>
  <td>555 77 855</td>
</tr>
</table>';

downloadWord($str, 'abc.doc');

運(yùn)行后的效果圖

PHP生成word文檔

PHP生成word文檔

轉(zhuǎn)載請(qǐng)標(biāo)明原文鏈接: http://www.itdecent.cn/p/3a59904c6898
更多精彩請(qǐng)?jiān)L問(wèn)個(gè)人博客:https://www.whmblog.cn/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,346評(píng)論 25 708
  • awesome-php 收集整理一些常用的PHP類庫(kù), 資源以及技巧. 以便在工作中迅速的查找所需... 這個(gè)列表...
    guanguans閱讀 4,767評(píng)論 0 34
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,684評(píng)論 4 61
  • 大雪過(guò)后 降雪的幾率增大 天氣也會(huì)愈發(fā)變得寒冷 狗狗過(guò)冬也將面臨一些小危險(xiǎn) 下面是天天訓(xùn)狗整理的幾點(diǎn)寵物過(guò)冬小貼士...
    天天訓(xùn)狗閱讀 456評(píng)論 0 0
  • 昨天孩子生病 ,去醫(yī)院吊水,那個(gè)哭的呦,心疼。今天接著吊水,因?yàn)槔鲜强薨装锥喟υ?針,看著孩子哭的那個(gè)聲音,心里...
    忽而之顛閱讀 185評(píng)論 0 0

友情鏈接更多精彩內(nèi)容