Home  >  Article  >  Backend Development  >  php导出生成word的方法_php技巧

php导出生成word的方法_php技巧

WBOY
WBOYOriginal
2016-05-16 20:01:521049browse

本文实例讲述了php导出生成word的方法。分享给大家供大家参考,具体如下:

PHP导出word

(1)首先,预览html页面,示例化对象,定义要导出的数据
(2)点击下载页面,给id传值(任何值均可,仅用于判断),如果id有值,输出缓冲文件,保存为word格式。
(3)点击下载后,(如果是图片的话,在保存为word时要使用绝对路径,这样才可以在保存的word中正常显示)
(4)关闭缓存输出

Word_con.php  预览要导出的html文件

<&#63;php
if(@$_GET[id]!='')
{
 include('word_fun.php');
 $word=new word();//示例化对象
 $word->start();//定义要保存数据的开始
}
include('word_show.php');
 if(@$_GET[id]!='')
 {
   $word->save('word_c.doc');//定义要保存数据的结束,同时把数据保存到word中
 }
 if(@$_GET[id]=='')
 {
 //超链接中的x仅仅是为了传一个值,确认下载,没有其他的实际yi
 &#63;>
 <a href="#"><div onclick="window.location.href='word_con.php&#63;id=x'">点击跳到下载页面</div></a>
 <&#63;php
 }else{
 echo "<a href=\"word_c.doc\">下载</a>";
 }
&#63;>

Word_fun.php  导出word相关函数

<&#63;php
class word
{
function start() //定义要保存数据的开始
{
    ob_start(); //开始输出缓冲
    //设置生成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) //定义要保存数据的结束,同时把数据保存到word中  
//所要保存的数据必须限定在该类的start()和save()之间
{
print "</html>";
$data=ob_get_contents(); //返回内部缓冲的内容 即把输出变成字符串
ob_end_clean(); //结束输出缓冲,清洁(擦除)输出缓冲区并关闭输出缓冲
$this->wirtetoword($path,$data);
}
function wirtetoword($fn,$data) //将数据已二进制的形式保存到word中
{
$fp=fopen($fn,"wb");
fwrite($fp,$data);
fclose($fp);
}
}
&#63;>

Word_show.php  连接数据库,查询相关数据

<&#63;php 
 include('conn.php'); //连接数据库
 $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'];
 }
&#63;>

希望本文所述对大家PHP程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn