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

來源:互聯網
上載者:User
php產生word文檔在學習中可以經常見到,本篇將介紹一種方法。

PHP產生word文檔,網上有很多方法,有調用COM組件產生的,有安裝PHP擴充產生的,也有引用第三方類庫,如phpword產生的。以下為最簡潔的兩種方法,無須安裝其他,只要你安裝了php環境便可以直接產生。

<?phpheader("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');

運行後的

PHP產生word文檔

PHP產生word文檔

本篇介紹了php產生word文檔的方法,更多相關內容請關注php中文網。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.