当前位置: 首页 > 编程文章 >

db2xml类核心方法与辅助函数解析

db2xml类核心方法与辅助函数解析

作者:沈禾时间:2025-04-11 16:18:55浏览:173

该代码片段展示了db2xml类的内部实现,涵盖从数据库结果到XML文档的转换逻辑。主要包含用于构建XML结构的insertNewResult、insertNewRow及insertNewElement方法,以及处理字符编码的xml_encode和兼容PHP 4.0.6版本的doXmlString2Xml辅助函数。此外,还提供了array_merge_clobber自定义合并算法,以及通过getXpathValue和getXpathChildValues执行XPath查询以提取特定数据的功能。

本文目录展开

{

配置选项与结构构建方法

if (is_array($value) && ! $delete)


                    {

foreach ($value as $suboption => $subvalue)


                        {

$this->{$option}["$suboption"] = $subvalue;


                        }
                    }

else


                    {

$this->$option = $value;


                    }
                }
            }
        }
    }

// these are the functions, which are intended to be overriden in user classes


    /**
    *

* @param mixed


* @return object DomNode


* @access private


    */
function insertNewResult(&$metadata)
        {
    if ($this->xmlroot)
    return $this->xmlroot->new_child($this->tagNameResult, NULL);
    else
            {
    $this->xmlroot = $this->xmldoc->add_root($this->tagNameResult);
    //PHP 4.0.6 had $root->name as tagname, check for that here...
    if (!isset($this->xmlroot->{$this->tagname}))
                {
    $this->tagname = "name";
                }
    return $this->xmlroot;
    
            }
    }

    /**

* to be written


    *

* @param object DomNode $parent_row


* @param mixed $res


* @param mixed $key


* @param mixed &metadata


* @return object DomNode


* @access private


    */
function insertNewRow($parent_row, $res, $key, &$metadata)
        {
    return $parent_row->new_child($this->tagNameRow, Null);
    }

    /**

* to be written


    *

* @param object DomNode $parent


* @param mixed $res


* @param mixed $key


* @param mixed &$metadata


* @param mixed &$subrow


* @return object DomNode


* @access private


    */
function insertNewElement($parent, $res, $key, &$metadata, &$subrow)
        {
    return $parent->new_child(metadata[$key]["name"], $this->xml_encode(trim$res[$key]));
    }

    /**

* to be written


    *

* @param mixed $key


* @param mixed $value


* @param mixed &$metadata


* @access private


    */
function addTableInfo($key, $value, &$metadata) {
    
    }

// end functions, which are intended to be overriden in user classes


// here come some helper functions...


    /**

* make utf8 out of the input data and escape & with & and "< " with "< "


* (we assume that when there's no space after < it's a tag, which we need in the xml)


* I'm not sure, if this is the standard way, but it works for me.


    *

* @param string text to be utfed.


* @access private


    */

function xml_encode ($text)


    {

if (function_exists("iconv") && isset($this->encoding_from) && isset($this->encoding_to))


        {

ini_set("track_errors",1);


$text = iconv($this->encoding_from,$this->encoding_to,ereg_replace("&","&",ereg_replace("< ","< ",$text)));


if (! isset($text) )


             {

if (isset($php_errormsg))


                {

$errormsg = "error: $php_errormsg";


                }

else


                {

$errormsg = "undefined iconv error, turn on track_errors in php.ini to get more details";


                }

return PEAR::raiseError($errormsg,Null,PEAR_ERROR_DIE);


             }

else {


return $text;


             }
        }

else


        {

//$text = utf8_encode(ereg_replace("&","&",ereg_replace("< ","< ",$text)));


$text = trim(ereg_replace("&","&",ereg_replace("< ","< ",$text)));


// echo $text;


        }

return $text;


    }

//taken from kc@hireability.com at http://www.php.net/manual/en/function.array-merge-recursive.php


    /**

* There seemed to be no built in function that would merge two arrays recursively and clobber


* any existing key/value pairs. Array_Merge() is not recursive, and array_merge_recursive


* seemed to give unsatisfactory results... it would append duplicate key/values.


    *

* So here's a cross between array_merge and array_merge_recursive


    **/
    /**
    *

* @param array first array to be merged


* @param array second array to be merged


* @return array merged array


* @access private


    */
function array_merge_clobber($a1,$a2)
        {
    if(!is_array($a1)
    !is_array($a2)) return false;
    $newarray = $a1;
    while (list($key, $val) = each($a2))
            {
    if (is_array($val) && is_array($newarray[$key]))
                {
    $newarray[$key] = $this->array_merge_clobber($newarray[$key], $val);
                }
    else
                {
    $newarray[$key] = $val;
                }
            }
    return $newarray;
    }
    /**

* Adds a xml string to $this->xmldoc.


* It's inserted on the same level as a "normal" resultset, means just as a children of


    * if a xpath expression is supplied, it takes that for selecting only part of the xml-file
    *
    * the clean code works only with php 4.0.7
    * for php4.0.6 :
    * I found no cleaner method than the below one. it's maybe nasty (xmlObject->string->xmlObject),
    * but it works. If someone knows how to add whole DomNodes to another one, let me know...
    *
    * @param string xml string
    * @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 private
    */
    function doXmlString2Xml ($string,$xpath = Null)
    {
        //check if we have a recent domxml. otherwise use the workaround...
        $version = explode(".",phpversion());
        if (! ($version[0] <= 4 and $version[1] <= 0 and $version[2] < 7) ){
            if (is_array($xpath))
            {
                if (isset($xpath["root"]))
                {
                    $root = $xpath["root"];
                }
                $xpath = $xpath["xpath"];
            }
            $tmpxml = xmldoc($string);
            $subroot = $this->xmlroot;
            if (isset($root))
            {
                $roots = explode("/",$root);
                foreach ($roots as $rootelement)
                {
                    if ( strlen($rootelement) > 0 )
                    {
                        $subroot = $subroot->new_child($rootelement,"");
                    }
                }
            }
            //$this->xmlroot->addchild does some strange things when added nodes from xpath.... so this comment helps out
            $newchild = $subroot->add_child($this->xmldoc->create_comment("the purpose of this comment is a workaround in sql2php.php line ".__LINE__));
            // if no xpath is given, just take the whole file
            if ( (is_null($xpath)))
            {
                $newchild->append_child($tmpxml->root());
            }
            else
            {
                $xctx = $tmpxml->xpath_new_context();
                $xnode = xpath_eval($xctx,$xpath);
                foreach ($xnode->nodeset as $node)
                {
                    $newchild->append_child($node);
                }
            }
         }
        else {
            $MainXmlString = $this->xmldoc->dumpmem();
            $string = preg_replace("/<\?xml.*\?>/","",$string);
            $MainXmlString = preg_replace("/<".$this->xmlroot->{$this->tagname}."\/>/","<".$this->xmlroot->{$this->tagname}.">".$this->xmlroot->{$this->tagname}.">",$MainXmlString);
            $MainXmlString = preg_replace("</".$this->xmlroot->{$this->tagname}.">/",$string."".$this->xmlroot->{$this->tagname}.">",$MainXmlString);
            $this->xmldoc = xmldoc($MainXmlString);
            $this->xmlroot = $this->xmldoc->root();
        }
    }
    /**
    * sets the encoding for the db2xml transformation
    * @param string $encoding_from encoding to transform from
    * @param string $encoding_to encoding to transform to
    * @access public
    */
    function setEncoding ($encoding_from = "ISO-8859-1", $encoding_to ="UTF-8")
    {
        $this->encoding_from = $encoding_from;
        $this->encoding_to = $encoding_to;
    }
    /**
    * @param array $parentTables parent to child relation
    * @access public
    */
    function SetParentTables($parentTables)
    {
        foreach ($parentTables as $table => $parent)
        {
            $table_info["parent_table"][$table]=$parent;
        }
        $this->SetOptions(array("user_tableInfo"=>$table_info));
    }
    /**
    * returns the content of the first match of the xpath expression
    *
    * @param string $expr xpath expression
    * @return mixed content of the evaluated xpath expression
    * @access public
    */
    function getXpathValue ($expr)
    {
        $xpth = $this->xmldoc->xpath_new_context();
        $xnode = xpath_eval($xpth,$expr);
        if (isset ($xnode->nodeset[0]))
        {
            $firstnode = $xnode->nodeset[0];
            $children = $firstnode->children();
            $value = $children[0]->content;
                return $value;
        }
        else
        {
            return Null;
        }
    }
    /**
    * get the values as an array from the childtags from the first match of the xpath expression
    *
    * @param string xpath expression
    * @return array with key->value of subtags
    * @access public
    */
    function getXpathChildValues ($expr)
    {
        $xpth = $this->xmldoc->xpath_new_context();
        $xnode = xpath_eval($xpth,$expr);
        if (isset ($xnode->nodeset[0]))
        {
            foreach ($xnode->nodeset[0]->children() as $child)
            {
                $children = $child->children();
                $value[$child->{$this->tagname}] = $children[0]->content;
            }
            return $value;
        }
        else
        {
            return Null;
        }
    }
}
?>
上一篇
简单理解PHP的面向对象编程方式

PHP同时支持面向过程和面向对象两种编程范式,开发者可根据项目需求自由选择或混合使用。虽然早期版本以过程式为主,但面向对象在代码结构清晰、易于维护和扩展方面具有显著优势。通过字符串过滤等具体场景对比可见,面向对象虽初期实例化稍显繁琐,但能提升长期开发效率并降低页面逻辑混乱度。

下一篇
PHP基础语法与常用函数速查

本文梳理了PHP开发中涉及的基本符号、变量形态、各类运算规则以及常用的字符串处理和类型检测函数。内容涵盖单双引号的区别、算术与位运算逻辑、htmlspecialchars转义、大小写转换及md5加密等核心知识点,并详细列举了is_int、isset等类型判断函数的具体用途,为初学者提供快速参考。

相关文章

更多
CodeIgniter扩展核心类与辅助函数详解

本文介绍CodeIgniter框架中扩展核心类、类库及辅助函数的具体方法。通过配置subclass_prefix前缀(默认为MY_),开发者可选择替换或继承system目录下的原有类,或在application/helpers中利用function_exists实现函数覆盖。这种机制允许在不修改系统源码的前提下灵活增强框架功能,确保升级时的代码安全性。

2025.10.10 910
解决XML命名空间导致XPath查询失效的问题 (C#与PHP)

在使用XPath获取XML文档数据时,若节点包含XMLNS属性定义的命名空间,直接编写路径表达式将返回空结果。本文以获取歌曲标题为例,说明如何通过C#的XmlNamespaceManager和PHP的registerXPathNamespace方法注册命名空间前缀,从而正确解析带命名空间的XML结构。

2025.02.20 739
Laravel框架常用目录路径辅助函数详解

本文介绍了Laravel框架中用于获取项目各核心目录绝对路径的辅助函数。通过app_path、base_path、config_path、database_path、public_path及storage_path等函数,开发者可以便捷地生成相对于特定目录的文件路径,例如使用app_path('Http/Controllers/Controller.php')获取控制器完整路径,或调用storage_path('app/file.txt')定位存储文件。这些函数简化了文件操作中的路径拼接逻辑。

2025.04.13 444
PHP实现中文数字转阿拉伯数字辅助函数

分享一个PHP辅助函数,用于尽可能识别并转换字符串中的中文数字为阿拉伯数字。该函数支持普通中文、大写中文、口语化表达及混合文本中的数字提取,例如将“九百六十万”转换为9600000。需注意该实现不支持小数,且无法处理超过PHP_INT_MAX的超大数值。

2026.02.02 380
PHP数组生成XML格式数据的封装类实例

本文介绍了一个用于将PHP数组转换为XML格式数据的封装类。该类通过递归处理数组节点,支持属性与子元素的嵌套结构,并提供写入文件的功能。文中提供了核心类库代码及测试用例,帮助开发者快速实现数据结构到XML的转换。

2025.07.02 373
Laravel5添加自定义辅助函数的四步实现法

Laravel框架内置了array_get、app_path等丰富辅助函数以提升开发效率。若需新增自定义辅助函数,可通过创建Helper文件、注册自动加载及重新编译autoload.php四步完成配置,实现全局调用。

2026.10.01 269

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。