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 相关文章推荐
Apache设置虚拟WEB
Oct 09 PHP
攻克CakePHP系列一 连接MySQL数据库
Oct 22 PHP
基于curl数据采集之单页面并行采集函数get_htmls的使用
Apr 28 PHP
php之Memcache学习笔记
Jun 17 PHP
ThinkPHP让分页保持搜索状态的方法
Jul 02 PHP
php官方微信接口大全(微信支付、微信红包、微信摇一摇、微信小店)
Dec 21 PHP
smarty中改进truncate使其支持中文的方法
May 30 PHP
关于php 高并发解决的一点思路
Apr 16 PHP
PHP结合Vue实现滚动底部加载效果
Dec 17 PHP
PHP一致性hash分布式算法封装类定义与用法示例
Aug 04 PHP
PHP生成二维码与识别二维码的方法详解【附源码下载】
Mar 07 PHP
PHP中的Iterator迭代对象属性详解
Apr 12 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新手谈谈我的学习心得
2007/02/25 PHP
mysql 搜索之简单应用
2007/04/27 PHP
用Zend Encode编写开发PHP程序
2010/02/21 PHP
zend optimizer在wamp的基础上安装图文教程
2013/10/26 PHP
PHP中strcmp()和strcasecmp()函数字符串比较用法分析
2016/01/07 PHP
JavaScript开发规范要求(规范化代码)
2010/08/16 Javascript
jquery实现点击弹出层效果的简单实例
2014/03/03 Javascript
jquery实现人性化的有选择性禁用鼠标右键
2014/06/30 Javascript
一款基于jQuery的图片场景标注提示弹窗特效
2015/01/05 Javascript
JavaScript实现简单的数字倒计时
2015/05/15 Javascript
JS实现网页上随滚动条滚动的层效果代码
2015/11/04 Javascript
Jquery1.9.1源码分析系列(六)延时对象应用之jQuery.ready
2015/11/24 Javascript
JavaScript实现点击单元格改变背景色的方法
2016/02/12 Javascript
理解javascript中的闭包
2017/01/11 Javascript
JS打开摄像头并截图上传示例
2017/02/18 Javascript
jquery简单实现纵向的无缝滚动代码实例
2019/04/01 jQuery
Vue使用自定义指令实现拖拽行为实例分析
2020/06/06 Javascript
简单介绍Python中的struct模块
2015/04/28 Python
Python模块结构与布局操作方法实例分析
2017/07/24 Python
python 类对象和实例对象动态添加方法(分享)
2017/12/31 Python
Django视图和URL配置详解
2018/01/31 Python
实例讲解Python中整数的最大值输出
2019/03/17 Python
Python远程方法调用实现过程解析
2020/07/28 Python
Django路由层URLconf作用及原理解析
2020/09/24 Python
纯CSS3绘制打火机动画火焰效果
2016/07/18 HTML / CSS
Chain Reaction Cycles芬兰:世界上最大的在线自行车商店
2017/12/06 全球购物
Fanatics英国官网:美国体育电商
2018/11/06 全球购物
如何实现一个自定义类的序列化
2012/05/22 面试题
房地产开发计划书
2014/01/10 职场文书
在校大学生的职业生涯规划书
2014/03/14 职场文书
2015年元旦文艺汇演主持词
2014/03/26 职场文书
孔繁森观后感
2015/06/10 职场文书
行政处罚事先告知书
2015/07/01 职场文书
餐厅服务员管理制度
2015/08/05 职场文书
机关单位2016年法制宣传日活动总结
2016/04/01 职场文书
使用numpy nonzero 找出非0元素
2021/05/14 Python