本文實(shí)例講述了php導(dǎo)出生成word的方法。分享給大家供大家參考,具體如下:
PHP導(dǎo)出word
(1)首先,預(yù)覽html頁(yè)面,示例化對(duì)象,定義要導(dǎo)出的數(shù)據(jù)
(2)點(diǎn)擊下載頁(yè)面,給id傳值(任何值均可,僅用于判斷),如果id有值,輸出緩沖文件,保存為word格式。
(3)點(diǎn)擊下載后,(如果是圖片的話,在保存為word時(shí)要使用絕對(duì)路徑,這樣才可以在保存的word中正常顯示)
(4)關(guān)閉緩存輸出
Word_con.php 預(yù)覽要導(dǎo)出的html文件
<?phpif(@$_GET[id]!=''){ include('word_fun.php'); $word=new word();//示例化對(duì)象 $word->start();//定義要保存數(shù)據(jù)的開(kāi)始}include('word_show.php'); if(@$_GET[id]!='') { $word->save('word_c.doc');//定義要保存數(shù)據(jù)的結(jié)束,同時(shí)把數(shù)據(jù)保存到word中 } if(@$_GET[id]=='') { //超鏈接中的x僅僅是為了傳一個(gè)值,確認(rèn)下載,沒(méi)有其他的實(shí)際yi ?> <a href="#"><div onclick="window.location.href='word_con.php?id=x'">點(diǎn)擊跳到下載頁(yè)面</div></a> <?php }else{ echo "<a href=/"word_c.doc/">下載</a>"; }?> Word_fun.php 導(dǎo)出word相關(guān)函數(shù)
<?phpclass word{function start() //定義要保存數(shù)據(jù)的開(kāi)始{ ob_start(); //開(kāi)始輸出緩沖 //設(shè)置生成word的格式 print '<html xmlns="urn:schemas-microsoft-comfficeffice" xmlns:w="urn:schemas-microsoft-comffice:word" xmlns="http://www.w3.org/TR/REC-html40">';}function save($path) //定義要保存數(shù)據(jù)的結(jié)束,同時(shí)把數(shù)據(jù)保存到word中 //所要保存的數(shù)據(jù)必須限定在該類的start()和save()之間{print "</html>";$data=ob_get_contents(); //返回內(nèi)部緩沖的內(nèi)容 即把輸出變成字符串ob_end_clean(); //結(jié)束輸出緩沖,清潔(擦除)輸出緩沖區(qū)并關(guān)閉輸出緩沖$this->wirtetoword($path,$data);}function wirtetoword($fn,$data) //將數(shù)據(jù)已二進(jìn)制的形式保存到word中{$fp=fopen($fn,"wb");fwrite($fp,$data);fclose($fp);}}?> Word_show.php 連接數(shù)據(jù)庫(kù),查詢相關(guān)數(shù)據(jù)
<?php include('conn.php'); //連接數(shù)據(jù)庫(kù) $sq="select zf_content from zf where `zf_id`=137"; $sql=mysql_query($sq); while(($que=mysql_fetch_array($sql))!=false) { echo "<font color=/"red/">hahaahahha</font>"; echo $que['zf_content']; }?> 希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。

















