把从SQL中取出的数据转化成XMl格式


Posted in PHP onOctober 09, 2006

使用了php的PEAR和DB
<?php
// +----------------------------------------------------------------------+
// | PHP version 4.0                                                      
|// +----------------------------------------------------------------------+
// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group             
|// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license,       
|// | that is bundled with this package in the file LICENSE, and is        
|// | available at through the world-wide-web at                           
|// | http://www.php.net/license/2_02.txt.                                 
|// | If you did not receive a copy of the PHP license and are unable to   
|// | obtain it through the world-wide-web, please send a note to          
|// | license@php.net so we can mail you a copy immediately.               
|// +----------------------------------------------------------------------+
// | Authors: Christian Stocker <chregu@phant.ch>                         
|// +----------------------------------------------------------------------+
//
// $Id: sql2xml.php,v 1.59 2001/11/13 10:54:02 chregu Exp $

/**
* This class takes a PEAR::DB-Result Object, a sql-query-string or an array
*  and returns a xml-representation of it.
*
* TODO
*   -encoding etc, options for header
*   -ERROR CHECKING
*
* Usage example
*
* include_once ("DB.php");
* include_once("XML/sql2xml.php");
* $db = DB::connect("mysql://root@localhost/xmltest");
* $sql2xml = new xml_sql2xml();
* //the next one is only needed, if you need others than the default
* $sql2xml->setEncoding("ISO-8859-1","UTF-8");
* $result = $db->query("select * from bands");
* $xmlstring = $sql2xml->getXML($result);
*
* or
*
* include_once ("DB.php");
* include_once("XML/sql2xml.php");
* $sql2xml = new xml_sql2xml("mysql://root@localhost/xmltest");
* $sql2xml->Add("select * from bands");
* $xmlstring = $sql2xml->getXML();
*
* More documentation and a tutorial/how-to can be found at
*   http://php.chregu.tv/sql2xml
*
* @author   Christian Stocker <chregu@bitflux.ch>
* @version  $Id: sql2xml.php,v 1.59 2001/11/13 10:54:02 chregu Exp $
* @package  XML
*/
class XML_sql2xml {

    /**
    * If joined-tables should be output nested.
    *  Means, if you have joined two or more queries, the later
    *   specified tables will be nested within the result of the former
    *   table.
    *   Works at the moment only with mysql automagically. For other RDBMS
    *   you have to provide your table-relations by hand (see user_tableinfo)
    *
    * @var  boolean
    * @see  $user_tableinfo, doSql2Xml(), doArray2Xml();
    */
    var $nested = True;

    /**
    * Name of the tag element for resultsets
    *
    * @var  string
    * @see  insertNewResult()
    */
    var $tagNameResult = "result";

    /**
    * Name of the tag element for rows
    *
    * @var  string
    * @see  insertNewRow()
    */
    var $tagNameRow = "row";

    /**
    *
    * @var   object PEAR::DB
    * @access private
    */
    var $db = Null;

    /**
    * Options to be used in extended Classes (for example in sql2xml_ext).
    * They are passed with SetOptions as an array (arrary("user_options" = array());
    *  and can then be accessed with $this->user_options["bla"] from your
    *  extended classes for additional features.
    *  This array is not use in this base class, it's only for passing easy parameters
    *  to extended classes.
    *
    * @var      array
    */
    var $user_options = array();

    /**
    * The DomDocument Object to be used in the whole class
    *
    * @var      object  DomDocument
    * @access    private
    */
    var $xmldoc;

    /**
    * The Root of the domxml object
    * I'm not sure, if we need this as a class variable....
    * could be replaced by domxml_root($this->xmldoc);
    *
    * @var      object DomNode
    * @access    private
    */
    var $xmlroot;

    /**
    * This array is used to give the structure of your database to the class.
    *  It's especially useful, if you don't use mysql, since other RDBMS than
    *  mysql are not able at the moment to provide the right information about
    *  your database structure within the query. And if you have more than 2
    *  tables joined in the sql it's also not possible for mysql to find out
    *  your real relations.
    *  The parameters are the same as in fieldInfo from the PEAR::DB and some
    *   additional ones. Here they come:
    *  From PEAR::DB->fieldinfo:
    *
    *    $tableInfo[$i]["table"]    : the table, which field #$i belongs to.
    *           for some rdbms/comples queries and with arrays, it's impossible
    *           to find out to which table the field actually belongs. You can
    *           specify it here more accurate. Or if you want, that one fields
    *           belongs to another table, than it actually says (yes, there's
    *           use for that, see the upcoming tutorial ...)
    *
    *    $tableInfo[$i]["name"]     : the name of field #$i. if you want another
    *           name for the tag, than the query or your array provides, assign
    *           it here.
    *
    *   Additional info
    *     $tableInfo["parent_key"][$table]  : index of the parent key for $table.
    *           this is the field, where the programm looks for changes, if this
    *           field changes, it assumes, that we need a new "rowset" in the
    *           parent table.
    *
    *     $tableInfo["parent_table"][$table]: name of the parent table for $table.
    *
    * @var      array
    * @access    private
    */
    var $user_tableInfo = array();

    /**
    * the encoding type, the input from the db has
    */
    var $encoding_from  = "ISO-8859-1";

    /**
    * the encoding type, the output in the xml should have
    * (note that domxml at the moment only support UTF-8, or at least it looks like)
    */
    var $encoding_to = "gb2312";

    var $tagname = "tagname";

    /**
    * Constructor
    * The Constructor can take a Pear::DB "data source name" (eg.
    *  "mysql://user:passwd@localhost/dbname") and will then connect
    *  to the DB, or a PEAR::DB object link, if you already connected
    *  the db before.
    "  If you provide nothing as $dsn, you only can later add stuff with
    *   a pear::db-resultset or as an array. providing sql-strings will
    *   not work.
    * the $root param is used, if you want to provide another name for your
    *  root-tag than "root". if you give an empty string (""), there will be no
    *  root element created here, but only when you add a resultset/array/sql-string.
    *  And the first tag of this result is used as the root tag.
    *
    * @param  mixed $dsn    PEAR::DB "data source name" or object DB object
    * @param  string $root  the name of the xml-doc root element.
    * @access   public
    */
    function XML_sql2xml ($dsn = Null, $root = "root") {

        // if it's a string, then it must be a dsn-identifier;

        if (is_string($dsn))
        {
            include_once ("DB.php");
            $this->db = DB::Connect($dsn);
            if (DB::isError($this->db))
            {
                print "The given dsn for XML_sql2xml was not valid in file ".__FILE__." at line ".__LINE__."<br>\n";
                return new DB_Error($this->db->code,PEAR_ERROR_DIE);
            }

        }

        elseif (is_object($dsn) && DB::isError($dsn))
        {
            print "The given param for XML_sql2xml was not valid in file ".__FILE__." at line ".__LINE__."<br>\n";
            return new DB_Error($dsn->code,PEAR_ERROR_DIE);
        }

        // if parent class is db_common, then it's already a connected identifier
        elseif (get_parent_class($dsn) == "db_common")
        {
            $this->db = $dsn;
        }

        $this->xmldoc = domxml_new_xmldoc('1.0');

        //oehm, seems not to work, unfortunately.... does anybody know a solution?
        $this->xmldoc->encoding = $this->encoding_to;        

        if ($root) {
            $this->xmlroot = $this->xmldoc->add_root($root);
            //PHP 4.0.6 had $root->name as tagname, check for that here...
            if (!isset($this->xmlroot->{$this->tagname}))
            {
                $this->tagname = "name";
            }
        }

    }

    /**
    * General method for adding new resultsets to the xml-object
    *  Give a sql-query-string, a pear::db_result object or an array as
    *  input parameter, and the method calls the appropriate method for this
    *  input and adds this to $this->xmldoc
    *
    * @param    string sql-string, or object db_result, or array
    * @param    mixed additional parameters for the following functions
    * @access   public
    * @see      addResult(), addSql(), addArray(), addXmlFile()
    */
    function add ($resultset, $params = Null)
    {

        // if string, then it's a query, a xml-file or a xml-string...
        if (is_string($resultset)) {
            if (preg_match("/\.xml$/",$resultset)) {
                $this->AddXmlFile($resultset,$params);
            }
            elseif (preg_match("/.*select.*from.*/i" ,  $resultset)) {
                $this->AddSql($resultset);
            }
            else {
                $this->AddXmlString($resultset);
            }

        }
        // if array, then it's an array...
        elseif (is_array($resultset)) {
            $this->AddArray($resultset);
        }

        if (get_class($resultset) == "db_result") {
            $this->AddResult($resultset);
        }
    }

    /**
    * Adds the content of a xml-file to $this->xmldoc, on the same level
    * as a normal resultset (mostly just below <root>)
    *
    * @param    string filename
    * @param    mixed xpath  either a string with the xpath expression or an array with "xpath"=>xpath expression  and "root"=tag/subtag/etc, which are the tags to be inserted before the result
    * @access   public
    * @see      doXmlString2Xml()
    */

    function addXmlFile($file,$xpath = Null)
    {
        $fd = fopen( $file, "r" );
        $content = fread( $fd, filesize( $file ) );
        fclose( $fd );
        $this->doXmlString2Xml($content,$xpath);
    }

    /**
    * Adds the content of a xml-string to $this->xmldoc, on the same level
    * as a normal resultset (mostly just below <root>)
    *
    * @param    string xml
    * @param    mixed xpath  either a string with the xpath expression or an array with "xpath"=>xpath expression  and "root"=tag/subtag/etc, which are the tags to be inserted before the result
    * @access   public
    * @see      doXmlString2Xml()
    */

PHP 相关文章推荐
在线竞拍系统的PHP实现框架(一)
Oct 09 PHP
php中global和$GLOBALS[]的分析之一
Feb 02 PHP
php对大文件进行读取操作的实现代码
Jan 23 PHP
PHP5中Cookie与 Session使用详解
Apr 30 PHP
PHP导航下拉菜单的实现如此简单
Sep 22 PHP
php中操作memcached缓存进行增删改查数据的实现代码
Aug 15 PHP
初识PHP
Sep 28 PHP
实现PHP+Mysql无限分类的方法汇总
Mar 02 PHP
PHP树的深度编历生成迷宫及A*自动寻路算法实例分析
Mar 10 PHP
PHP 等比例缩放图片详解及实例代码
Sep 18 PHP
Python中使用django form表单验证的方法
Jan 16 PHP
ThinkPHP 模板引擎使用详解
May 07 PHP
JAVA/JSP学习系列之四
Oct 09 #PHP
JAVA/JSP学习系列之二
Oct 09 #PHP
递归列出所有文件和目录
Oct 09 #PHP
不用iconv库的gb2312与utf-8的互换函数
Oct 09 #PHP
PHP的历史和优缺点
Oct 09 #PHP
新版PHP将向Java靠拢
Oct 09 #PHP
JAVA/JSP学习系列之七
Oct 09 #PHP
You might like
php初学者写及时补给skype用户充话费的小程序
2008/11/02 PHP
PHP更新购物车数量(表单部分/PHP处理部分)
2013/05/03 PHP
mac环境中使用brew安装php5.5.15
2014/08/18 PHP
PHP生成腾讯云COS接口需要的请求签名
2018/05/20 PHP
一个多次搜索+多次传值的解决方案
2007/01/20 Javascript
javascript getElementsByTagName
2011/01/31 Javascript
jQuery中的.bind()、.live()和.delegate()之间区别分析
2011/06/08 Javascript
解析javascript系统错误:-1072896658的解决办法
2013/07/08 Javascript
Jquery日期选择datepicker插件用法实例分析
2015/06/08 Javascript
深入剖析JavaScript:Object类型
2016/05/10 Javascript
AngularJS 模块化详解及实例代码
2016/09/14 Javascript
原生JS仿QQ阅读点击展开、收起效果
2017/03/08 Javascript
windows下vue-cli及webpack搭建安装环境
2017/04/25 Javascript
深入解析nodejs HTTP服务
2017/07/25 NodeJs
vue-cli脚手架config目录下index.js配置文件的方法
2018/03/13 Javascript
JS编写兼容IE6,7,8浏览器无缝自动轮播
2018/10/12 Javascript
简单的React SSR服务器渲染实现
2018/12/11 Javascript
vue-cli3添加模式配置多环境变量的方法
2019/06/05 Javascript
python实现关闭第三方窗口的方法
2019/06/28 Python
python Qt5实现窗体跟踪鼠标移动
2019/12/13 Python
Python定时器线程池原理详解
2020/02/26 Python
python中tab键是什么意思
2020/06/18 Python
python多线程semaphore实现线程数控制的示例
2020/08/10 Python
美国儿童珠宝在线零售商:Loveivy
2019/05/22 全球购物
企业文化口号
2014/06/12 职场文书
门面房租房协议书
2014/08/20 职场文书
幼儿园教师师德师风演讲稿:我自豪我是一名幼师
2014/09/10 职场文书
教师党的群众路线教育实践活动个人整改措施
2014/11/04 职场文书
武当山导游词
2015/02/03 职场文书
信访工作个人总结
2015/03/03 职场文书
超搞笑婚前保证书
2015/05/08 职场文书
百年校庆宣传标语口号
2015/12/26 职场文书
小学新课改心得体会
2016/01/22 职场文书
立秋之描写立秋的作文(五年级)
2019/08/08 职场文书
导游词之山西-五老峰
2019/10/07 职场文书
Python实现视频自动打码的示例代码
2022/04/08 Python