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 相关文章推荐
中国站长站 For Dede4.0 采集规则
May 27 PHP
php生成随机数或者字符串的代码
Sep 05 PHP
PHP中的生成XML文件的4种方法分享
Oct 06 PHP
php实现文件下载更能介绍
Nov 23 PHP
php json_encode值中大括号与花括号区别
Sep 30 PHP
10 个经典PHP函数
Oct 17 PHP
php动态生成版权所有信息的方法
Mar 24 PHP
php基于curl扩展制作跨平台的restfule 接口
May 11 PHP
PHP简单实现DES加密解密的方法
Jul 12 PHP
php基于自定义函数记录log日志方法
Jul 21 PHP
PHP数组常用函数实例小结
Aug 20 PHP
Yii2框架控制器、路由、Url生成操作示例
May 27 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 skymvc 一款轻量、简单的php
2011/06/28 PHP
php下获取http状态的实现代码
2014/05/09 PHP
php+ajax实现文章自动保存的方法
2014/12/30 PHP
PHP的Laravel框架中使用消息队列queue及异步队列的方法
2016/03/21 PHP
JavaScript 动态创建VML的方法
2009/10/14 Javascript
js用正则表达式来验证表单(比较齐全的资源)
2013/11/17 Javascript
JQuery弹出层示例可自定义
2014/05/19 Javascript
javascript中this指向详解
2016/04/23 Javascript
Web打印解决方案之普通报表打印功能
2016/08/29 Javascript
Vuejs 用$emit与$on来进行兄弟组件之间的数据传输通信
2017/02/23 Javascript
微信小程序之网络请求简单封装实例详解
2017/06/28 Javascript
详解node+express+ejs+bootstrap构建项目
2017/09/27 Javascript
js canvas实现红包照片效果
2018/08/21 Javascript
React注册倒计时功能的实现
2018/09/06 Javascript
layui点击按钮页面会自动刷新的解决方案
2019/10/25 Javascript
JavaScript实现无限轮播效果
2020/11/19 Javascript
Python转码问题的解决方法
2008/10/07 Python
Python中分数的相关使用教程
2015/03/30 Python
Python优化技巧之利用ctypes提高执行速度
2016/09/11 Python
python使用正则表达式的search()函数实现指定位置搜索功能
2017/11/10 Python
Python中一行和多行import模块问题
2018/04/01 Python
python 常用的基础函数
2018/07/10 Python
Python如何获得百度统计API的数据并发送邮件示例代码
2019/01/27 Python
使用django实现一个代码发布系统
2019/07/18 Python
详解Python 实现 ZeroMQ 的三种基本工作模式
2020/03/24 Python
Python Matplotlib绘图基础知识代码解析
2020/08/31 Python
解决使用Pandas 读取超过65536行的Excel文件问题
2020/11/10 Python
中东地区最大的奢侈品市场:The Luxury Closet
2019/04/09 全球购物
德国领先的大尺码和超大尺码男装在线零售商:Bigtex
2019/06/22 全球购物
Mountain Hardwear官网:攀岩服装和户外装备
2019/09/26 全球购物
客户表扬信范文
2014/01/10 职场文书
彩色的翅膀教学反思
2014/04/25 职场文书
爱耳日活动总结
2014/04/30 职场文书
2014年客房部工作总结
2014/11/22 职场文书
Java字符缓冲流BufferedWriter
2022/04/09 Java/Android
Windows Server 2008配置防火墙策略详解
2022/06/28 Servers