保存word
在实际工作中经常需要将数据库中的一些相关数据备份到word文档中;如果通过人工的方式将数据库中的数据按部就班的录入到word文档中虽然可以实现数据的备份,但会在很大程度上降低效率。现在介绍一种通过自定义函数将数据库中的数据保存到word的方法;
这里是在实现数据库中的数据保存到文档中的时候,主要通过word实现
这个类中应用了输出控制函数ob_start(),ob_get_content(),ob_end_clean()以及文件操作系统函数fopen(),fwrite()和fclose();
1.ob_start()函数
开启缓存,这时将不会有来自脚本的内容被输出,这些内容都存储在缓存里
bool ob_start ( [callback output_callback [, int chunk_size [, bool erase]]] )
ob_start()函数的参数说明如表1所示。
|
参数 |
说明 |
|
output_callback |
可选参数。设置回叫函数,当遇到ob_end_flush()函数的时候或者在脚本末尾缓存自动输出的时候,回叫函数才被执行。函数会收到以输出的内容作为参数,并且函数需要返回一个包括新内容的变量 |
|
chunk_size |
可选参数。设置每行输出内容的字节数,达到设置的字节数就会换行 |
|
erase |
可选参数。如果设置为false,那么在脚本结束后,缓存不会被删除,作用于php 4.3.0之后 |
2.ob_get_contents()函数
获取缓存中的内容,失败则返回false。
string ob_get_contents ( void )
3.ob_end_clean()函数
清除输出缓存中的内容,并关闭缓存,成功返回true,失败则返回false。
bool ob_end_clean ( void )
创建word类,将定义到test.php中 word类关键代码如下;
<?php
// header("content_type:text/html;charset=utf8");//反面教材
header("Content-type: text/html; charset=utf-8");
class word{
function start(){
ob_start();
}
function save($path){
$data=ob_get_contents();
ob_end_clean();
$this->writetoword($path,$data);
}
function writetoword($fn,$data){
$fp=fopen($fn, "wb");
fwrite($fp, $data);
fclose($fp);
}
}
在该类中定义了三个成员函数,实现的功能如下:
(1)start():该成员函数的作用是定制要保存数据的开始。
(2)save():该成员函数的作用是定制要保存数据的结束,同时执行将数据库中的数据保存到Word中的操作,也就是说所要保存的数据必须限定在该类的成员函数start()和成员函数save()之间。
(3)wirtetoword():该成员函数的作用是实现将数据以二进制的形式保存到Word中。
创建数据库连接文件以及数据输出页面,然后调用word类中的方法将数据库中的数据保存到word文件中;代码如下
<?php
$conn=@mysql_connect("localhost","root","") or die("数据库连接失败");
mysql_select_db("hnthdl",$conn)or die("数据库连接失败");
mysql_query("set names utf8");
if(@$_GET["id"]!=""){
include_once("test.php");
$word=new word();
$word->start();
}?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<table>
<tr>
<td>
<table>
<tr>
<td>
<div>商品名称</div>
</td>
<td>
<div>出产日期</div>
</td>
<td>
<div>作者</div>
</td>
<td>
<div>相关</div>
</td>
</tr>
<?php
include_once("./test.php");
$sql=mysql_query("select * from hnthdl_archives order by id desc",$conn);
$info=mysql_fetch_array($sql);
if($info==false){
echo "没有这个商品信息";
}else{
do{
?>
<tr>
<td>
<div><?php echo $info["title"]; ?> </div>
</td>
<td>
<div><?php echo $info["pubdate"] ?> </div>
</td>
<td>
<div><?php echo $info["writer"] ?> </div>
</td>
<td>
<div><?php echo $info["keywords"] ?> </div>
</td>
</tr>
<?php
}
while($info=mysql_fetch_array($sql)) ;
}
if(@$_GET["id"]!=""){
$word->save("data.doc");
}
if(@$_GET["id"]==""){
?>
<tr>
<td>
<div>
<input type="button" name="submit" value="内容保存到word"class="buttoncss" onclick="window.location.href='index.php?id=print'">
</div>
</td>
</tr>
<?php
}else{
echo "<div>表格数据已经保存到word中</div>";
}
?>
</table>
</td>
</tr>
</table>
</body>
</html>

浙公网安备 33010602011771号