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缓存技术介绍
Nov 25 PHP
php设计模式 Visitor 访问者模式
Jun 28 PHP
Php图像处理类代码分享
Jan 19 PHP
php Ubb代码编辑器函数代码
Jul 05 PHP
php获取目标函数执行时间示例
Mar 04 PHP
php约瑟夫问题解决关于处死犯人的算法
Mar 23 PHP
php格式化电话号码的方法
Apr 24 PHP
PHP递归遍历多维数组实现无限分类的方法
May 06 PHP
利用PHP访问带有密码的Redis方法示例
Feb 09 PHP
浅析PHP数据导出知识点
Feb 17 PHP
Laravel框架查询构造器简单示例
May 08 PHP
微信小程序发送订阅消息的方法(php 为例)
Oct 30 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
DC动画电影《黑暗正义联盟》曝预告 5月5日上线数字平台
2020/04/09 欧美动漫
PHP在Web开发领域的优势
2006/10/09 PHP
PHP实现单例模式最安全的做法
2014/06/13 PHP
php从完整文件路径中分离文件目录和文件名的方法
2015/03/13 PHP
php实现的顺序线性表示例
2019/05/04 PHP
PHP大文件切割上传功能实例分析
2019/07/01 PHP
Yii框架布局文件的动态切换操作示例
2019/11/11 PHP
js获取客户端外网ip的简单实例
2013/11/21 Javascript
javascript 终止函数执行操作
2014/02/14 Javascript
判断日期是否能跨月查询的js代码
2014/07/25 Javascript
JavaScript中的包装对象介绍
2015/01/27 Javascript
jQuery判断对象是否存在的方法
2015/02/05 Javascript
原生js制作简单的数字键盘
2015/04/24 Javascript
Bootstrap基本插件学习笔记之模态对话框(16)
2016/12/08 Javascript
vue-router 中router-view不能渲染的解决方法
2017/05/23 Javascript
微信小程序之滚动视图容器的实现方法
2017/09/26 Javascript
解决vuejs 使用value in list 循环遍历数组出现警告的问题
2018/09/26 Javascript
angularJs自定义过滤器实现手机号信息隐藏的方法
2018/10/08 Javascript
JavaScript中AOP的实现与应用
2019/05/06 Javascript
合并Excel工作薄中成绩表的VBA代码,非常适合教育一线的朋友
2009/04/09 Python
python hbase读取数据发送kafka的方法
2018/12/27 Python
python实现扫描局域网指定网段ip的方法
2019/04/16 Python
ubuntu 16.04下python版本切换的方法
2019/06/14 Python
一行Python代码过滤标点符号等特殊字符
2019/08/12 Python
python装饰器代替set get方法实例
2019/12/19 Python
python爬虫开发之Request模块从安装到详细使用方法与实例全解
2020/03/09 Python
html5中localStorage本地存储的简单使用
2017/06/16 HTML / CSS
印度最大的旅游网站:MakeMyTrip
2016/10/05 全球购物
计算s=f(f(-1.4))的值
2014/05/06 面试题
2013年大学生的自我鉴定
2013/10/24 职场文书
咖啡蛋糕店创业计划书
2014/01/28 职场文书
小学生节约用水倡议书
2014/05/15 职场文书
理发店策划方案
2014/06/05 职场文书
事业单位财务人员岗位职责
2015/04/14 职场文书
Python实现生活常识解答机器人
2021/06/28 Python
Mysql存储过程、触发器、事件调度器使用入门指南
2022/01/22 MySQL