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 相关文章推荐
ip签名探针
Oct 09 PHP
PHP 表单提交给自己
Jul 24 PHP
PHP教程 基本语法
Oct 23 PHP
codeigniter框架The URI you submitted has disallowed characters错误解决方法
May 06 PHP
Smarty变量调节器失效的解决办法
Aug 20 PHP
php从字符串创建函数的方法
Mar 16 PHP
php实现统计网站在线人数的方法
May 12 PHP
YII2.0之Activeform表单组件用法实例
Jan 09 PHP
PHP与Java对比学习日期时间函数
Jul 03 PHP
老生常谈PHP位运算的用途
Mar 12 PHP
iis6手工创建网站后无法运行php脚本的解决方法
Jun 08 PHP
Yii2处理密码加密及验证的方法
May 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 Stream_*系列函数
2010/08/01 PHP
PHP中Socket连接及读写数据超时问题分析
2016/07/19 PHP
PHP实现微信提现功能(微信商城)
2019/11/21 PHP
jQuery寻找n以内完全数的方法
2015/06/24 Javascript
jQuery对html元素的取值与赋值实例详解
2015/12/18 Javascript
常用原生JS兼容性写法汇总
2016/04/27 Javascript
原生JS封装Ajax插件(同域、jsonp跨域)
2016/05/03 Javascript
利用JQuery直接调用asp.net后台的简单方法
2016/10/27 Javascript
浅谈MVC+EF easyui dataGrid 动态加载分页表格
2016/11/10 Javascript
laydate.js日期时间选择插件
2017/01/04 Javascript
浅谈Vue render函数在ElementUi中的应用
2018/09/06 Javascript
在Vue中获取组件声明时的name属性方法
2018/09/12 Javascript
React手稿之 React-Saga的详解
2018/11/12 Javascript
vue.js 2.*项目环境搭建、运行、打包发布的详细步骤
2019/05/01 Javascript
Vue动态组件和异步组件原理详解
2019/05/06 Javascript
Node.js 获取微信JS-SDK CONFIG的方法示例
2019/05/21 Javascript
[00:32]2018DOTA2亚洲邀请赛VG出场
2018/04/03 DOTA
python中合并两个文本文件并按照姓名首字母排序的例子
2014/04/25 Python
Python利用IPython提高开发效率
2016/08/10 Python
Django-celery-beat动态添加周期性任务实现过程解析
2020/11/26 Python
NUK奶瓶美国官网:NUK美国
2016/09/26 全球购物
简述数组与指针的区别
2014/01/02 面试题
C# .NET面试题
2015/11/28 面试题
抄作业检讨书
2014/02/17 职场文书
保险公司晨会主持词
2014/03/22 职场文书
《宿建德江》教学反思
2014/04/23 职场文书
保护环境倡议书100字
2014/05/19 职场文书
第二批党的群众路线教育实践活动个人对照检查材料
2014/09/23 职场文书
写给孩子的新学期寄语
2015/02/27 职场文书
保送生自荐信范文
2015/03/26 职场文书
周恩来的四个昼夜观后感
2015/06/03 职场文书
党风廉政承诺书2016
2016/03/25 职场文书
详解python网络进程
2021/06/15 Python
浅谈Redis中的RDB快照
2021/06/29 Redis
阿里云日志过滤器配置日志服务
2022/04/09 Servers
MySQL中LAG()函数和LEAD()函数的使用
2022/08/14 MySQL