PHP实现的XML操作类【XML Library】


Posted in PHP onDecember 29, 2016

本文实例讲述了PHP实现的XML操作类。分享给大家供大家参考,具体如下:

这是一个接口程序,需要大量分析解析XML,PHP的xml_parse_into_struct()函数不能直接生成便于使用的数组,而SimpleXML扩展在PHP5中才支持,于是逛逛搜索引擎,在老外的网站上找到了一个不错的PHP XML操作类。

一、用法举例:

1、将XML文件解释成便于使用的数组:

<?php
include('xml.php'); //引用PHP XML操作类
$xml = file_get_contents('data.xml'); //读取XML文件
//$xml = file_get_contents("php://input"); //读取POST过来的输入流
$data=XML_unserialize($xml);
echo '<pre>';
print_r($data);
echo '</pre>';
?>

data.xml文件:

<?xml version="1.0" encoding="GBK"?>
<video>
<upload>
<videoid>998</videoid>
<name><![CDATA[回忆未来]]></name>
<memo><![CDATA[def]]></memo>
<up_userid>11317</up_userid>
</upload>
</video>

利用该XML操作类生成的对应数组(汉字编码:UTF-8):

Array
(
 [video] => Array
  (
   [upload] => Array
    (
     [videoid] => 998
     [name] => 回忆未来
     [memo] => def
     [up_userid] => 11317
    )
  )
)

2、将数组转换成XML文件:

<?php
include('xml.php');//引用PHP XML操作类
$xml = XML_serialize($data);
?>

二、PHP XML操作类源代码:

<?php
###################################################################################
# XML_unserialize: takes raw XML as a parameter (a string)
# and returns an equivalent PHP data structure
###################################################################################
function & XML_unserialize(&$xml){
 $xml_parser = &new XML();
 $data = &$xml_parser->parse($xml);
 $xml_parser->destruct();
 return $data;
}
###################################################################################
# XML_serialize: serializes any PHP data structure into XML
# Takes one parameter: the data to serialize. Must be an array.
###################################################################################
function & XML_serialize(&$data, $level = 0, $prior_key = NULL){
 if($level == 0){ ob_start(); echo '<?xml version="1.0" ?>',"\n"; }
 while(list($key, $value) = each($data))
  if(!strpos($key, ' attr')) #if it's not an attribute
   #we don't treat attributes by themselves, so for an emptyempty element
   # that has attributes you still need to set the element to NULL
   if(is_array($value) and array_key_exists(0, $value)){
    XML_serialize($value, $level, $key);
   }else{
    $tag = $prior_key ? $prior_key : $key;
    echo str_repeat("\t", $level),'<',$tag;
    if(array_key_exists("$key attr", $data)){ #if there's an attribute for this element
     while(list($attr_name, $attr_value) = each($data["$key attr"]))
      echo ' ',$attr_name,'="',htmlspecialchars($attr_value),'"';
     reset($data["$key attr"]);
    }
    if(is_null($value)) echo " />\n";
    elseif(!is_array($value)) echo '>',htmlspecialchars($value),"</$tag>\n";
    else echo ">\n",XML_serialize($value, $level+1),str_repeat("\t", $level),"</$tag>\n";
   }
 reset($data);
 if($level == 0){ $str = &ob_get_contents(); ob_end_clean(); return $str; }
}
###################################################################################
# XML class: utility class to be used with PHP's XML handling functions
###################################################################################
class XML{
 var $parser; #a reference to the XML parser
 var $document; #the entire XML structure built up so far
 var $parent; #a pointer to the current parent - the parent will be an array
 var $stack; #a stack of the most recent parent at each nesting level
 var $last_opened_tag; #keeps track of the last tag opened.
 function XML(){
   $this->parser = &xml_parser_create();
  xml_parser_set_option(&$this->parser, XML_OPTION_CASE_FOLDING, false);
  xml_set_object(&$this->parser, &$this);
  xml_set_element_handler(&$this->parser, 'open','close');
  xml_set_character_data_handler(&$this->parser, 'data');
 }
 function destruct(){ xml_parser_free(&$this->parser); }
 function & parse(&$data){
  $this->document = array();
  $this->stack = array();
  $this->parent = &$this->document;
  return xml_parse(&$this->parser, &$data, true) ? $this->document : NULL;
 }
 function open(&$parser, $tag, $attributes){
  $this->data = ''; #stores temporary cdata
  $this->last_opened_tag = $tag;
  if(is_array($this->parent) and array_key_exists($tag,$this->parent)){ #if you've seen this tag before
   if(is_array($this->parent[$tag]) and array_key_exists(0,$this->parent[$tag])){ #if the keys are numeric
    #this is the third or later instance of $tag we've come across
    $key = count_numeric_items($this->parent[$tag]);
   }else{
    #this is the second instance of $tag that we've seen. shift around
    if(array_key_exists("$tag attr",$this->parent)){
     $arr = array('0 attr'=>&$this->parent["$tag attr"], &$this->parent[$tag]);
     unset($this->parent["$tag attr"]);
    }else{
     $arr = array(&$this->parent[$tag]);
    }
    $this->parent[$tag] = &$arr;
    $key = 1;
   }
   $this->parent = &$this->parent[$tag];
  }else{
   $key = $tag;
  }
  if($attributes) $this->parent["$key attr"] = $attributes;
  $this->parent = &$this->parent[$key];
  $this->stack[] = &$this->parent;
 }
 function data(&$parser, $data){
  if($this->last_opened_tag != NULL) #you don't need to store whitespace in between tags
   $this->data .= $data;
 }
 function close(&$parser, $tag){
  if($this->last_opened_tag == $tag){
   $this->parent = $this->data;
   $this->last_opened_tag = NULL;
  }
  array_pop($this->stack);
  if($this->stack) $this->parent = &$this->stack[count($this->stack)-1];
 }
}
function count_numeric_items(&$array){
 return is_array($array) ? count(array_filter(array_keys($array), 'is_numeric')) : 0;
}
?>
PHP 相关文章推荐
PHP Ajax中文乱码问题解决方法
Feb 27 PHP
php与php MySQL 之间的关系
Jul 17 PHP
PHP 采集获取指定网址的内容
Jan 05 PHP
PHP CURL模拟登录新浪微博抓取页面内容 基于EaglePHP框架开发
Jan 16 PHP
ThinkPHP无限级分类原理实现留言与回复功能实例
Oct 31 PHP
PHP防止注入攻击实例分析
Nov 03 PHP
分享最受欢迎的5款PHP框架
Nov 27 PHP
PHP处理会话函数大总结
Aug 05 PHP
PHP中子类重载父类的方法【parent::方法名】
May 06 PHP
PHP身份证校验码计算方法
Aug 10 PHP
laravel5.4生成验证码的实例讲解
Aug 05 PHP
PHP基于ip2long实现IP转换整形
Dec 11 PHP
php常用字符函数实例小结
Dec 29 #PHP
php常用正则函数实例小结
Dec 29 #PHP
详解ThinkPHP3.2.3验证码显示、刷新、校验
Dec 29 #PHP
php常用数组函数实例小结
Dec 29 #PHP
php正则修正符用法实例详解
Dec 29 #PHP
PHP登录(ajax提交数据和后台校验)实例分享
Dec 29 #PHP
php preg_match的匹配不同国家语言实例
Dec 29 #PHP
You might like
Ubuntu中启用php的mail()函数并解决发送邮件速度慢问题
2015/03/27 PHP
PHP简单生成缩略图相册的方法
2015/07/29 PHP
thinkPHP+mysql+ajax实现的仿百度一下即时搜索效果详解
2019/07/15 PHP
深入分析PHP设计模式
2020/06/15 PHP
利用Ext Js生成动态树实例代码
2008/09/08 Javascript
js去空格技巧分别去字符串前后、左右空格
2013/10/21 Javascript
JavaScript获取鼠标移动时的坐标(兼容IE8、chome谷歌、Firefox)
2014/09/13 Javascript
使表格的标题列可左右拉伸jquery插件封装
2014/11/24 Javascript
javascript闭包的理解
2015/04/01 Javascript
基于jquery实现的仿优酷图片轮播特效代码
2016/01/13 Javascript
JS实现Select的option上下移动的方法
2016/03/01 Javascript
JavaScript Base64 作为文件上传的实例代码解析
2017/02/14 Javascript
JavaScript实现替换字符串中最后一个字符的方法
2017/03/07 Javascript
ES6正则表达式的一些新功能总结
2017/05/09 Javascript
深入理解vue中的$set
2017/06/01 Javascript
原生JS实现旋转轮播图+文字内容切换效果【附源码】
2018/09/29 Javascript
Vux+Axios拦截器增加loading的问题及实现方法
2018/11/08 Javascript
原生javascript中this几种常见用法总结
2020/02/24 Javascript
如何使用three.js 制作一个三维的推箱子游戏
2020/07/29 Javascript
python 实现调用子文件下的模块方法
2018/12/07 Python
Python统计分析模块statistics用法示例
2019/09/06 Python
Python3监控疫情的完整代码
2020/02/20 Python
python 模拟登录B站的示例代码
2020/12/15 Python
HTML5 Video/Audio播放本地文件示例介绍
2013/11/18 HTML / CSS
html5表单及新增的改良元素详解
2016/06/07 HTML / CSS
Html5 webRTC简单实现视频调用的示例代码
2020/09/23 HTML / CSS
机电专业个人求职信范文
2013/12/30 职场文书
12岁生日感言
2014/01/21 职场文书
幼儿园安全检查制度
2014/01/30 职场文书
消防安全标语
2014/06/07 职场文书
学习十八大的心得体会
2014/09/12 职场文书
党员民主生活会对照检查材料思想汇报
2014/09/28 职场文书
催款函范文
2015/06/24 职场文书
2016教师政治学习心得体会
2016/01/23 职场文书
网络安全倡议书(3篇)
2019/09/18 职场文书
CSS3 实现NES游戏机的示例代码
2021/04/21 HTML / CSS