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

使用了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()
    */

(0)

相关推荐

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

    使用了php的PEAR和DB<?php// +----------------------------------------------------------------------+// | PHP version 4.0                                                      |// +----------------------------------------------------------------------+// | C

  • 从MySQL数据库表中取出随机数据的代码

    MySQL 如何从表中取出随机数据  以前在群里讨论过这个问题,比较的有意思.mysql的语法真好玩. 他们原来都想用PHP的实现随机,但取出多条好像要进行两次以上查询. 翻了手册,找到了下面这个语句,可以完成任务了 SELECT * FROM table_name ORDER BY rand() LIMIT 5; rand在手册里是这么说的: RAND()  RAND(N)  返回在范围0到1.0内的随机浮点值.如果一个整数参数N被指定,它被用作种子值.  mysql> select RAND

  • 详解Python中如何将数据存储为json格式的文件

    一.基于json模块的存储.读取数据 names_writer.py import json names = ['joker','joe','nacy','timi'] filename='names.json' with open(filename,'w') as file_obj: json.dump(names,file_obj) 解释:我们先导入json模块,再创建一个名字列表,第5行我们指定了要将该列表存储到其中的文件的名称.通常使用扩展名.json来指出文件存储的数据为json格式.

  • Vue 实现把表单form数据 转化成json格式的数据

    目的:Vue 中 把表单form数据 转化成json格式的数据 第一步:创建一个数据集(就是你表单需要的数据) 如果你表单都是一些正常的数据,比如 text 什么的.你定义好数据集,就去用 v-model 绑定数据.这样就可以实现数据同步了. 数据集 v-model绑定 如果你的数据不全是这种可以用 v-model 绑定的数据,比如我这个里面需要获取一个 img 的 src 的值.那么下面就需要你想办法把数据给绑定上去了 第二步:转化json 上面第一步,我们已经通过 自动 + 手动 的方式把我

  • 通过SQL语句直接把表导出为XML格式

    首先建立一张表: 复制代码 代码如下: USE [ip] GO /****** 对象: Table [dbo].[SiteData] 脚本日期: 09/11/2010 17:41:11 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[SiteData]( [id] [int] IDENTITY(1,1) NOT NULL, [SiteName]

  • Ruby中使用Nokogiri包来操作XML格式数据的教程

    安装 对于Ubuntu,需要安装好 libxml2, libxslt 这两个组件: $ apt-get install libxml2 libxslt 然后就可以: $ gem install nokogiri 可选项 nokogiri提供了一些解析文件时的可选项,常用的有: NOBLANKS : 删除空节点 NOENT : 替代实体 NOERROR : 隐藏错误报告 STRICT : 精确解析,当解析到文件异常时抛出错误 NONET : 在解析期间禁止任何网络连接. 可选项使用方式举例(通过块

  • 把HTML表单提交的数据转化成XML文件

    通常,在asp中进行的form表单提交的数据都被写进数据库管理系统中去,如果你想要你的数据是方便携带的数据,你可以把它写进一个XML文件中去.这种方法是跨平台的,因此你所收集的信息不需要进行转换. 为了实现上面的想法,你必须先利用Microsoft XMLDOM建立一个XML文件,Microsoft XMLDOM对象有一个扩展对象库,它可以创建组成XML文件所需要的元素.属性.属性值.     当XMLDOM对象实例化以后,必须对各个元素进行引用来建立XML的结构,下面的例子就是先建立根元素,并

  • PHP生成和获取XML格式数据的方法

    本文实例讲述了PHP生成和获取XML格式数据的方法.分享给大家供大家参考,具体如下: 在做数据接口时,我们通常要获取第三方数据接口或者给第三方提供数据接口,而这些数据格式通常是以XML或者JSON格式传输,这里将介绍如何使用PHP生成XML格式数据供第三方调用以及如何获取第三方提供的XML数据. 生成XML格式数据 我们假设系统中有一张学生信息表student,需要提供给第三方调用,并有id,name,sex,age分别记录学生的姓名.性别.年龄等信息. CREATE TABLE `studen

  • pytorch 把图片数据转化成tensor的操作

    摘要: 在图像识别当中,一般步骤是先读取图片,然后把图片数据转化成tensor格式,再输送到网络中去.本文将介绍如何把图片转换成tensor. 一.数据转换 把图片转成成torch的tensor数据,一般采用函数:torchvision.transforms.通过一个例子说明,先用opencv读取一张图片,然后在转换:注意一点是:opencv储存图片的格式和torch的储存方式不一样,opencv储存图片格式是(H,W,C),而torch储存的格式是(C,H,W). import torchvi

  • SQL中limit函数语法与用法(MYSQL获取限制某行数据)

    1.limit函数的语法和用法 (1)常用且简单的语法和用法 ①语法:limit n 即limit <参数> 具体语法:select <字段1>,...,<字段n> from <表名> (where <条件> order by <字段1>...<字段n> asc|desc) limit n 说明:括号内的语句可省略 参数说明: n:为阿拉伯数字,表示前n行. ②用法:用于获取前n行数据. (2)另一种(两个参数)语法和用法

随机推荐