今天是:
首 页信息查询网站SEO查询工具CSS编辑器建站素材
网海拾贝,电脑资讯,电脑快报,it资讯,网站建设资讯,教程基地
软件新闻
操作系统
Vista Winxp Win2003 Linux Windows综合
工具软件
系统工具 媒体工具 网络工具 杀毒软件 聊天
软件开发
C教程 C++ Java C# ASP.NET JSP PHP
数据库
Oracle MySQL DB2 SQL Server Sybase
安全
网络 病毒
办公应用
Word Excel Powerpoint Outlook 其他
平面设计
Photoshop Fireworks Coreldraw Flash Illustrator 3dsmax
网站运营
网站运营 网站优化 网站策划 策划书下载 建站心得 站长故事 网站盈利 网页制作 网页特效 建站素材 免费资源 QQ频道
  当前位置:首 页 >> 软件开发 >> PHP教程 >> php数据库导出类 导出JSON,XML,WORD,EXCEL

php数据库导出类 导出JSON,XML,WORD,EXCEL

  发布于2008-04-21 14:52 来源:phpchina 作者:04007147

本类实现:

  数据库信息导出:word,excel,json,xml,sql
  数据库恢复:从sql,从文件

具体用法:

首先新建测试用数据库mytest,然后在里面建张表

PHP代码:

以下是代码片段:
-- 
-- 表的结构 `test`
-- 
CREATE TABLE `test` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(100) NOT NULL,
  `email` varchar(200) NOT NULL,
  `age` int(3) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
-- 
-- 导出表中的数据 `test`
-- 
INSERT INTO `test` (`id`, `name`, `email`, `age`) VALUES 
(1, 'pjq518', [email=]'pjq518@126.com'[/email], 22),
(2, 'xiaoyu', [email=]'xiaoyu@126.com'[/email], 21);


1.导出ext能方便调用的json

PHP代码:

以下是代码片段:
 $db=new db();
echo  $db->toExtJson('test');

//输出结果为
//{'totalCount':'2','rows':[{'id':'1','name':'pjq518','email':'pjq518@126.com','age':'22'},{'id':'2','name':'xiaoyu','email':'xiaoyu@126.com','age':'21'}]}


toExtJson( $table, $start="0", $limit="10", $cons="")有4个参数, $table为表名, $cons为条件,可以为string或array
2导出xml

PHP代码:

以下是代码片段:
 $db=new db();
echo  $db->toExtXml('test');


//输出结果
 

3导出excel和word

PHP代码:

以下是代码片段:
 $db=new db();
//toExcel
 $map=array('No','Name','Email','Age');//表头
 $db->toExcel('test', $map,'档案');
//导出word表格
// $db->toWord('test', $map,'档案');


//效果如下图


PHP代码:

以下是代码片段:
<?php
class Db
{
var  $conn;
function Db( $host="localhost", $user="root", $pass="", $db="mytest")
{
  if(! $this->conn=mysql_connect( $host, $user, $pass))
  die("can't connect to mysql sever");
  mysql_select_db( $db, $this->conn);
  mysql_query("SET NAMES 'UTF-8'");
}
function execute( $sql)
{
   return mysql_query( $sql, $this->conn);
}
function findCount( $sql)
{
     $result= $this->execute( $sql);
    return mysql_num_rows( $result);
}
function findBySql( $sql)
{
     $array=array();
     $result=mysql_query( $sql);
     $i=0;
    while( $row=mysql_fetch_assoc( $result))
       {
       $array[ $i]= $row; 
    $i++;
       }
    return  $array;
}
// $con的几种情况
//空:返回全部记录
//array:eg. array('id'=>'1') 返回id=1的记录
//string :eg. 'id=1' 返回id=1的记录
function toExtJson( $table, $start="0", $limit="10", $cons="")
{
    $sql= $this->generateSql( $table, $cons);
    $totalNum= $this->findCount( $sql);
    $result= $this->findBySql( $sql." LIMIT ". $start." ,". $limit);
    $resultNum = count( $result);//当前结果数
   $str="";
   $str.= "{";
   $str.= "'totalCount':' $totalNum',";
   $str.="'rows':";
   $str.="[";
  for( $i=0; $i< $resultNum; $i++){
    $str.="{"; 
    $count=count( $result[ $i]);
    $j=1;
   foreach( $result[ $i] as  $key=> $val)
   {
   if( $j< $count)
   {
    $str.="'". $key."':'". $val."',";
   }
   elseif( $j== $count)
   {
    $str.="'". $key."':'". $val."'";
   }
    $j++;
            }
   
    $str.="}";
   if ( $i !=  $resultNum-1) {
              $str.= ",";
         }
  }
   $str.="]";
   $str.="}";
  return  $str;  
}
function generateSql( $table, $cons)
{
     $sql="";//sql条件
    $sql="select * from ". $table;
   if( $cons!="")
   {
   if(is_array( $cons))
   {
      $k=0;
     foreach( $cons as  $key=> $val)
  {
  if( $k==0)
  {
   $sql.="where '";
   $sql.= $key;
   $sql.="'='";
   $sql.= $val."'";
  }else
  {
   $sql.="and '";
   $sql.= $key;
   $sql.="'='";
   $sql.= $val."'";
  }
   $k++;
  }
   }else
   {
    $sql.=" where ". $cons;
   }
   }
   return  $sql;
}
function toExtXml( $table, $start="0", $limit="10", $cons="")
{
    $sql= $this->generateSql( $table, $cons);
    $totalNum= $this->findCount( $sql);
    $result= $this->findBySql( $sql." LIMIT ". $start." ,". $limit);
    $resultNum = count( $result);//当前结果数
      header("Content-Type: text/xml");
    $xml="<?xml version="1.0"  encoding="utf-8" ?>n";
    $xml.="<xml>n";
    $xml.="t<totalCount>". $totalNum."</totalCount>n";
    $xml.="t<items>n";
   for( $i=0; $i< $resultNum; $i++){
    $xml.="tt<item>n";
   foreach( $result[ $i] as  $key=> $val)
    $xml.="ttt<". $key.">". $val."</". $key.">n";
    $xml.="tt</item>n";
   }
     $xml.="t</items>n";
     $xml.="</xml>n";
    return  $xml;
}
//输出word表格
function toWord( $table, $mapping, $fileName)
{
   header('Content-type: application/doc'); 
      header('Content-Disposition: attachment; filename="'. $fileName.'.doc"'); 
      echo '<html xmlns:o="urn:schemas-microsoft-com:office:office" 
       xmlns:w="urn:schemas-microsoft-com:office:word" 
       xmlns="[url=http://www.w3.org/TR/REC-html40]http://www.w3.org/TR/REC-html40[/url]">
    <head>
       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>'. $fileName.'</title>
    </head>
    <body>'; 
    echo'<table border=1><tr>';
    if(is_array( $mapping))
    {
      foreach( $mapping as  $key=> $val)
   echo'<td>'. $val.'</td>';
    }
    echo'</tr>';
     $results= $this->findBySql('select * from '. $table);
    foreach( $results as  $result)
    {
      echo'<tr>';
      foreach( $result as  $key=> $val)
   echo'<td>'. $val.'</td>';
   echo'</tr>';
    }
    echo'</table>';
    echo'</body>';
    echo'</html>';
}
function toExcel( $table, $mapping, $fileName)
{
  header("Content-type:application/vnd.ms-excel");
     header("Content-Disposition:filename=". $fileName.".xls");
  echo'<html xmlns:o="urn:schemas-microsoft-com:office:office"
       xmlns:x="urn:schemas-microsoft-com:office:excel"
       xmlns="[url=http://www.w3.org/TR/REC-html40]http://www.w3.org/TR/REC-html40[/url]">
       <head>
       <meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT">
       <meta http-equiv=Content-Type content="text/html; charset=iso-8859-1">
       <!--[if gte mso 9]><xml>
       <x:ExcelWorkbook>
       <x:ExcelWorksheets>
               <x:ExcelWorksheet>
               <x:Name></x:Name>
               <x:WorksheetOptions>
                       <x:DisplayGridlines/>
               </x:WorksheetOptions>
               </x:ExcelWorksheet>
       </x:ExcelWorksheets>
       </x:ExcelWorkbook>
       </xml><![endif]-->
       </head>
    <body link=blue vlink=purple leftmargin=0 topmargin=0>'; 
    echo'<table width="100%" border="0" cellspacing="0" cellpadding="0">';
       echo'<tr>';
    if(is_array( $mapping))
    {
      foreach( $mapping as  $key=> $val)
   echo'<td>'. $val.'</td>';
    }
    echo'</tr>';
     $results= $this->findBySql('select * from '. $table);
    foreach( $results as  $result)
    {
      echo'<tr>';
      foreach( $result as  $key=> $val)
   echo'<td>'. $val.'</td>';
   echo'</tr>';
    }
    echo'</table>';
    echo'</body>';
    echo'</html>';
}
function Backup( $table)
{
  if(is_array ( $table))
  {
    $str="";
   foreach( $table as  $tab)
    $str.= $this->get_table_content( $tab);
   return  $str;
  }else{
   return  $this->get_table_content( $table);
  }
}
function Backuptofile( $table, $file)
{
  header("Content-disposition: filename= $file.sql");//所保存的文件名
  header("Content-type: application/octetstream");
  header("Pragma: no-cache");
  header("Expires: 0");
  if(is_array ( $table))
  {
    $str="";
   foreach( $table as  $tab)
    $str.= $this->get_table_content( $tab);
   echo  $str;
  }else{
   echo  $this->get_table_content( $table);
  }
}
function Restore( $table, $file="", $content="")
{
  //排除file,content都为空或者都不为空的情况
  if(( $file==""&& $content=="")||( $file!=""&& $content!=""))
  echo"参数错误";
   $this->truncate( $table);
  if( $file!="")
  {
   if( $this->RestoreFromFile( $file))
   return true;
   else
   return false;
  }
  if( $content!="")
  {
   if( $this->RestoreFromContent( $content))
   return true;
   else
   return false;
  }
}
//清空表,以便恢复数据
function truncate( $table)
{
  if(is_array ( $table))
  {
    $str="";
   foreach( $table as  $tab)
    $this->execute("TRUNCATE TABLE  $tab");
  }else{
    $this->execute("TRUNCATE TABLE  $table");
  }
}
function get_table_content( $table)
{
   $results= $this->findBySql("select * from  $table");
   $temp = "";
   $crlf="rn";
  foreach( $results as  $result)
  {
   
   /*(";
  foreach( $result as  $key=> $val)
  {
    $schema_insert .= " `". $key."`,";
  }
   $schema_insert = ereg_replace(", $", "",  $schema_insert);
   $schema_insert .= ") 
  */
   $schema_insert = "INSERT INTO   $table VALUES (";
  foreach( $result as  $key=> $val)
  {
   if( $val != "")
    $schema_insert .= " '".addslashes( $val)."',";
   else
    $schema_insert .= "NULL,";
  }
   $schema_insert = ereg_replace(", $", "",  $schema_insert);
   $schema_insert .= "); $crlf";
   $temp =  $temp. $schema_insert ;
  }
  return  $temp;
}
function RestoreFromFile( $file){
  if (false !== ( $fp = fopen( $file, 'r'))) {
    $sql_queries = trim(fread( $fp, filesize( $file)));
    $this->splitMySqlFile( $pieces,  $sql_queries);
   foreach ( $pieces as  $query) {
    if(! $this->execute(trim( $query)))
    return false;
   }
   return true;
  }
  return false;
}
function RestoreFromContent( $content)
{
   $content = trim( $content);
   $this->splitMySqlFile( $pieces,  $content);
  foreach ( $pieces as  $query) {
   if(! $this->execute(trim( $query)))
   return false;
  }
  return true;
}
function splitMySqlFile(& $ret,  $sql)
{
   $sql= trim( $sql);
   $sql=split(';', $sql);
   $arr=array();
  foreach( $sql as  $sq)
  {
    if( $sq!="");
     $arr[]= $sq;
  }
   $ret= $arr;
  return true;
}
}
 $db=new db();
 $map=array('No','Name','Email','Age');
// $db->toExcel('test', $map,'档案');
echo  $db->toExtXml('test');
?>


中查找“php数据库导出类 导出JSON,XML,WORD,EXCEL”更多相关内容

中查找“php数据库导出类 导出JSON,XML,WORD,EXCEL”更多相关内容



上一篇:PHP与数据库试题 Zend权威认证试题讲解
下一篇:Ajax+PHP简单入门教程
最近更新 赞助商
·PHP单件模式结合命令链模式10-31
·取消网页缓存的html,asp,php代码10-28
·php时间比较函数DateDiff10-28
·php left函数 解决中文被截成乱码的问题10-28
·PHP上传类源码 瑞意上传类 RUpload10-28
·Windows Server 2008系统IIS7中PHP环境的..10-21
·PHP开发的Myers 订单跟踪系统 (MOTS)09-18
·php教程:php设计模式介绍之适配器模式08-22
·php使用curl模拟用户登陆08-21
·php的curl实现get和post08-18
·Perl操作mysql数据库的方法08-18

共有评论 0 条 网友评分 0分 查看所有评论


发表评论→ 学而不思则罔,思而不学则殆,请大胆发表你的见解。

输验证码:

您对此篇文章的评分:1分 2分 3分 4分 5分

  • 站内搜索
关键词

搜索方式

搜索范围

精确匹配
Baidu
网站首页 - 关于本站 - 网站地图 - 广告合作 - 站点声明 - RSS订阅 - 联系我们
Copyright © 2005 网海拾贝.[新ICP备05003216号]. All Rights Reserved .