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学习笔记 [预定义数组(超全局数组)]
Jun 09 PHP
PHP+Mysql+jQuery实现发布微博程序 jQuery篇
Oct 08 PHP
深入PHP中慎用双等于(==)的详解
Jun 06 PHP
迅速确定php多维数组的深度的方法
Jan 07 PHP
PHP下获取上个月、下个月、本月的日期(strtotime,date)
Feb 02 PHP
php读取mssql的ntext字段返回值为空的解决方法
Dec 30 PHP
DEDECMS首页调用图片集里的多张图片
Jun 05 PHP
Linux系统递归生成目录中文件的md5的方法
Jun 29 PHP
php多线程并发实现方法
Sep 30 PHP
php生成与读取excel文件
Oct 14 PHP
PHP的mysqli_thread_id()函数讲解
Jan 24 PHP
Laravel使用RabbitMQ的方法示例
Jun 18 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实现股票趋势图和柱形图
2015/02/07 PHP
PHP中STDCLASS用法实例分析
2016/11/11 PHP
搭建自己的PHP MVC框架详解
2017/08/16 PHP
PHP设计模式之装饰器模式实例详解
2018/02/07 PHP
前淘宝前端开发工程师阿当的PPT中有JS技术理念问题
2010/01/15 Javascript
判断控件是否已加载完成的代码
2010/02/24 Javascript
图片延迟加载的实现代码(模仿懒惰)
2013/03/29 Javascript
怎么选择Javascript框架(Javascript Framework)
2013/11/22 Javascript
javascript表单验证使用示例(javascript验证邮箱)
2014/01/07 Javascript
基于jQuery实现下拉框
2014/11/24 Javascript
jquery队列函数用法实例
2014/12/16 Javascript
js实现时间显示几天前、几小时前或者几分钟前的方法集锦
2015/05/29 Javascript
AngularJS基础 ng-keydown 指令简单示例
2016/08/02 Javascript
基于react组件之间的参数传递(详解)
2017/09/05 Javascript
基于JavaScript实现五子棋游戏
2020/08/26 Javascript
抖音上用记事本编写爱心小程序教程
2019/04/17 Javascript
TypeScript开发Node.js程序的方法
2019/04/30 Javascript
Vue 实现从文件中获取文本信息的方法详解
2019/10/16 Javascript
Vue最新防抖方案(必看篇)
2019/10/30 Javascript
vue2.0 解决抽取公用js的问题
2020/07/31 Javascript
vue-cli打包后本地运行dist文件中的index.html操作
2020/08/12 Javascript
[01:01:24]LGD vs Fnatic 2018国际邀请赛小组赛BO2 第一场 8.18
2018/08/19 DOTA
python获取图片颜色信息的方法
2015/03/18 Python
python3爬虫学习之数据存储txt的案例详解
2019/04/24 Python
opencv python图像梯度实例详解
2020/02/04 Python
基于Python编写一个计算器程序,实现简单的加减乘除和取余二元运算
2020/08/05 Python
全面解析CSS Media媒体查询使用操作(推荐)
2017/08/15 HTML / CSS
amazeui时间组件的实现示例
2020/08/18 HTML / CSS
IWOOT美国:新奇的小玩意
2018/04/27 全球购物
电子商务个人自荐信
2013/12/12 职场文书
公司应聘求职信
2014/06/21 职场文书
国庆庆典邀请函
2015/02/02 职场文书
预备党员表决心的话
2015/09/22 职场文书
JS Object构造函数之Object.freeze
2021/04/28 Javascript
一篇文章学会Vue中间件管道
2021/06/20 Vue.js
CSS浮动引起的高度塌陷问题
2022/08/05 HTML / CSS