当前位置: 首页 > 编程文章 >

PHP XML操作类:解析与生成数组互转方案

PHP XML操作类:解析与生成数组互转方案

作者:苏舟时间:2026-01-19 16:28:12浏览:147

针对PHP5前环境或需灵活控制XML结构的场景,介绍一款第三方XML操作类。该类解决了xml_parse_into_struct()返回结构复杂及SimpleXML版本限制问题,支持将XML文件高效转换为易用的关联数组,并可将数组还原为XML格式。本文提供具体使用示例、核心代码逻辑及相关在线辅助工具推荐。

本文目录展开

PHP XML操作类背景与优势

本文详细介绍一个基于PHP开发的XML操作类库,旨在为开发者提供便捷的XML数据处理能力,供参考与实践。

在开发涉及大量XML分析与解析的接口程序时,PHP内置的函数往往难以直接生成结构清晰、易于操作的数组对象。虽然SimpleXML扩展提供了更友好的API,但其仅在PHP5及以上版本中可用。考虑到兼容性与功能需求,本文引入了一款源自国外开源社区的实用PHP XML操作类,以解决上述痛点。

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 '</code></pre>';
?&gt;

假设存在如下结构的文件内容:


<?xml version="1.0" encoding="GBK"?>


998
回忆未来
def
11317



使用该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);
?>

XML操作类核心代码实现

二、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; } ?>

配套在线XML工具推荐

此外,为方便日常开发调试,以下推荐几款实用的在线XML处理工具:

在线XML与JSON格式互相转换工具: 点击使用

在线XML格式化与压缩工具: 点击使用

希望本文提供的XML操作类及相关资料能对您的PHP程序设计工作有所帮助。

上一篇
PHPMailer实现HTML邮件发送与附件功能详解

本文介绍如何使用PHPMailer类库在PHP环境中发送包含HTML内容和图片附件的电子邮件。文章详细说明了前端表单交互、后端通过jQuery AJAX调用以及利用163 SMTP服务器进行身份验证和邮件发送的核心代码逻辑,帮助开发者快速集成邮件发送功能。

下一篇
PHP mysql_select_db函数选择数据库详解

mysql_select_db 是 PHP 中用于切换当前连接的默认数据库的函数。该函数接受两个参数,其中 database 为必需参数,指定要选择的数据库名称;connection 为可选参数,若未指定则使用上一个已建立的 MySQL 连接。执行成功时返回 true,失败则返回 false。

相关文章

更多
PHP操作XML文件:增删改查完整示例与工具推荐

本文通过index.php与demo2.xml的完整案例,详细演示了PHP对XML文件进行增加、删除、修改和查询的具体实现方法。同时整理了多款实用的在线XML转换、格式化及压缩工具,帮助开发者高效处理XML数据。

2025.03.28 814
PHP使用DOMDocument读取XML版本信息示例

本文介绍如何使用PHP的DOMDocument类读取存放软件版本信息的XML文件。通过加载指定路径的xml文件,遍历updataMessages节点获取version和newmsg字段,实现版本比对与更新提示功能,并附带相关在线工具推荐。

2025.10.02 761
PHP XML解析工具类与在线辅助资源

本文介绍了一个PHP XML解析工具类的实现思路,涵盖资源管理、编码设置及结构存储等核心属性。同时提供了XML与JSON互转、XML格式化与压缩等在线实用工具链接,旨在帮助开发者高效处理XML数据并简化日常操作流程。

2026.06.23 650
PHP使用SimpleXML生成与解析XML详解

本文介绍PHP中SimpleXML库的使用方法,重点讲解如何通过addchild、addAttribute和asXml方法生成XML字符串及文件,以及如何利用simplexml_load_file或simplexml_load_string解析XML数据。相比DOMDocument等其他方式,SimpleXML操作更为简洁高效。

2026.04.17 303
PHP4与PHP5解析XML文档的方法对比及SimpleXML使用详解

本文详细对比了PHP4和PHP5版本中解析XML文档的不同方法。重点介绍了PHP5中基于DOM的SimpleXML扩展,涵盖文件读取、节点遍历、XPath查询及数据修改等核心操作;同时回顾了PHP4自带的SAX解析器实现步骤。通过代码实例展示两种方式的差异,帮助开发者根据需求选择合适的解析方案。

2025.03.09 271
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,031

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
XML 与 JSON 互转
XML 与 JSON 互转

在 XML 与 JSON 表示之间转换,辅助整理接口返回和配置数据。

XML 格式化与压缩
XML 格式化与压缩

展开或压缩 XML 文本,检查标签层级,便于阅读与接口调试。

键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。