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数组的交集array_intersect(),array_intersect_assoc(),array_inter_key()函数的小问题
May 29 PHP
php smarty 二级分类代码和模版循环例子
Jun 16 PHP
PHP中替换换行符的几种方法小结
Oct 15 PHP
浅析使用Turck-mmcache编译来加速、优化PHP代码
Jun 20 PHP
php采用curl实现伪造IP来源的方法
Nov 21 PHP
php实现的简单检验登陆类
Jun 18 PHP
6个超实用的PHP代码片段
Aug 10 PHP
[原创]php实现子字符串位置相互对调互换的方法
Jun 02 PHP
PHP针对多用户实现更换头像功能
Sep 04 PHP
php车辆违章查询数据示例
Oct 14 PHP
PHP实现多级分类生成树的方法示例
Feb 07 PHP
PHP 断点续传实例详解
Nov 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
PHP创建单例后台进程的方法示例
2017/05/23 PHP
PHP ADODB实现分页功能简单示例
2018/05/25 PHP
Laravel框架自定义公共函数的引入操作示例
2019/04/16 PHP
JS 添加千分位与去掉千分位的示例
2013/07/11 Javascript
调用innerHTML之后onclick失效问题的解决方法
2014/01/28 Javascript
JavaScript实现的图像模糊算法代码分享
2014/04/22 Javascript
jquery禁用右键示例
2014/04/28 Javascript
IE6兼容透明背景图片及解决方案
2015/08/19 Javascript
js实现tab选项卡切换功能
2017/01/13 Javascript
js cookie实现记住密码功能
2017/01/17 Javascript
详解AngularJS controller调用factory
2017/05/19 Javascript
利用webstrom调试Vue.js单页面程序的方法教程
2017/06/06 Javascript
JavaScript去掉数组重复项的方法分析【测试可用】
2018/07/19 Javascript
JavaScript面向对象程序设计中对象的定义和继承详解
2019/07/29 Javascript
Element 默认勾选表格 toggleRowSelection的实现
2019/09/04 Javascript
Vue组件通信入门之Provide和Inject机制
2019/12/29 Javascript
[19:59]2014DOTA2国际邀请赛 IG战队纪录片
2014/08/07 DOTA
Python SqlAlchemy动态添加数据表字段实例解析
2018/02/07 Python
Odoo中如何生成唯一不重复的序列号详解
2018/02/10 Python
Python基于递归和非递归算法求两个数最大公约数、最小公倍数示例
2018/05/21 Python
Python数据分析matplotlib设置多个子图的间距方法
2018/08/03 Python
Python使用scipy模块实现一维卷积运算示例
2019/09/05 Python
python pip安装包出现:Failed building wheel for xxx错误的解决
2019/12/25 Python
python切片作为占位符使用实例讲解
2021/02/17 Python
Spartoo瑞典:鞋子、包包和衣服
2018/09/15 全球购物
毕业生自荐书
2013/12/18 职场文书
建筑经济管理专业求职信分享
2014/01/06 职场文书
大学学习生活感言
2014/01/18 职场文书
春节联欢会主持词
2014/03/24 职场文书
4s店市场专员岗位职责
2014/04/09 职场文书
初中升旗仪式演讲稿
2014/05/08 职场文书
员工三分钟演讲稿
2014/08/19 职场文书
音乐教育专业自荐信
2014/09/18 职场文书
复兴之路纪录片观后感
2015/06/02 职场文书
2015年校医个人工作总结
2015/07/24 职场文书
二年级数学教学反思
2016/02/16 职场文书