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+.htaccess实现全站静态HTML文件GZIP压缩传输(一)
Feb 15 PHP
逐步提升php框架的性能
Jan 10 PHP
常用的PHP数据库操作方法(MYSQL版)
Jun 08 PHP
php skymvc 一款轻量、简单的php
Jun 28 PHP
php 检查电子邮件函数(自写)
Jan 16 PHP
PHP魔术引号所带来的安全问题分析
Jul 15 PHP
thinkphp数据查询和遍历数组实例
Nov 28 PHP
PHP正则验证Email的方法
Jun 15 PHP
PHP检测链接是否存在的代码实例分享
May 06 PHP
PHP学习笔记之php文件操作
Jun 03 PHP
thinkphp3.2中实现phpexcel导出带生成图片示例
Feb 14 PHP
php readfile下载大文件失败的解决方法
May 22 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学习笔记 IIS7下安装配置php环境
2012/10/29 PHP
php 获取今日、昨日、上周、本月的起始时间戳和结束时间戳的方法
2013/09/28 PHP
PHP简单读取xml文件的方法示例
2017/04/20 PHP
Laravel框架使用Seeder实现自动填充数据功能
2018/06/13 PHP
Laravel 简单实现Ajax滚动加载示例
2019/10/22 PHP
jquery实现漫天雪花飞舞的圣诞祝福雪花效果代码分享
2015/08/20 Javascript
javascript实现全角转半角的方法
2016/01/23 Javascript
jquery取消事件冒泡的三种方法(推荐)
2016/05/28 Javascript
AngularJS表单验证中级篇(3)
2016/09/28 Javascript
浅谈JavaScript的自动垃圾收集机制
2016/12/15 Javascript
JS多文件上传的实例代码
2017/01/11 Javascript
vue项目中跳转到外部链接的实例讲解
2018/09/20 Javascript
vue项目中,main.js,App.vue,index.html的调用方法
2018/09/20 Javascript
Vue CLI 3搭建vue+vuex最全分析(推荐)
2018/09/27 Javascript
node微信开发之获取access_token+自定义菜单
2019/03/17 Javascript
Javascript基于OOP实实现探测器功能代码实例
2020/08/26 Javascript
基于vue实现微博三方登录流程解析
2020/11/04 Javascript
Python 调用Java实例详解
2017/06/02 Python
Python用imghdr模块识别图片格式实例解析
2018/01/11 Python
python实现决策树ID3算法的示例代码
2018/05/30 Python
对sklearn的使用之数据集的拆分与训练详解(python3.6)
2018/12/14 Python
python绘制多个子图的实例
2019/07/07 Python
解决reload(sys)后print失效的问题
2020/04/25 Python
分享unittest单元测试框架中几种常用的用例加载方法
2020/12/02 Python
你不知道的葡萄干处理法、橙蜜处理法、二氧化碳酵母法
2021/03/17 冲泡冲煮
美国背景检查、公共记录和人物搜索网站:BeenVerified
2018/02/25 全球购物
eBay奥地利站:eBay.at
2019/07/24 全球购物
Jack Rogers官网:美国经典的女性鞋靴品牌
2019/09/04 全球购物
2019史上最全Database工程师题库
2015/12/06 面试题
String s = new String(“xyz”);创建了几个String Object?
2015/08/05 面试题
《我在为谁工作》:工作的质量往往决定生活的质量
2019/12/27 职场文书
如何理解Vue前后端数据交互与显示
2021/05/10 Vue.js
Python实现机器学习算法的分类
2021/06/03 Python
opencv检测动态物体的实现
2021/07/21 Python
MySQL磁盘碎片整理实例演示
2022/04/03 MySQL
Python序列化模块JSON与Pickle
2022/06/05 Python