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

PHP XML与数据格式转换类实现

PHP XML与数据格式转换类实现

作者:江川时间:2026-05-13 09:35:39浏览:686

该PHP类实现了XML与数组等数据格式之间的相互转换功能。通过递归遍历数组节点,能够自动生成符合规范的XML字符串结构,并支持对输出结果进行特定的标签清理处理,适用于需要频繁在结构化数据与XML之间切换的PHP应用场景。

本文目录展开

本示例展示了一个用于在PHP中实现XML与各类数据格式相互转换的工具类。相关内容可供开发者参考使用,具体实现细节如下文所示。

PHP实现XML与数据格式进行转换类实例


<?php
/**
 * xml2array() will convert the given XML text to an array in the XML structure. 
 * Link: http://www.bin-co.com/php/scripts/xml2array/ 
 * Arguments : $contents - The XML text 
 * $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value. 
 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure. 
 * Examples: $array = xml2array(file_get_contents('feed.xml')); 
 * $array = xml2array(file_get_contents('feed.xml', 1, 'attribute'));
 */
function xml2array($contents, $get_attributes = 1, $priority = 'tag') {
  if (!$contents) return array();
  if (!function_exists('xml_parser_create')) {
    // print "'xml_parser_create()' function not found!";
    return array();
  } 
  // Get the XML parser of PHP - PHP must have this module for the parser to work
  $parser = xml_parser_create('');
  xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss 
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  xml_parse_into_struct($parser, trim($contents), $xml_values);
  xml_parser_free($parser);
  if (!$xml_values) return; //Hmm... 
  // Initializations
  $xml_array = array();
  $parents = array();
  $opened_tags = array();
  $arr = array();
  $current = &$xml_array; //Refference 
  // Go through the tags.
  $repeated_tag_index = array(); //Multiple tags with same name will be turned into an array 
  foreach($xml_values as $data) {
    unset($attributes, $value); //Remove existing values, or there will be trouble 
    // This command will extract these variables into the foreach scope
    // tag(string), type(string), level(int), attributes(array).
    extract($data); //We could use the array by itself, but this cooler. 
    $result = array();
    $attributes_data = array();
    if (isset($value)) {
      if ($priority == 'tag') $result = $value;
      else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode 
    } 
    // Set the attributes too.
    if (isset($attributes) and $get_attributes) {
      foreach($attributes as $attr => $val) {
        if ($priority == 'tag') $attributes_data[$attr] = $val;
        else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr' 
      } 
    } 
    // See tag status and do the needed.
    if ($type == "open") { // The starting of the tag '<tag>'
      $parent[$level-1] = &$current;
      if (!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
        $current[$tag] = $result;
        if ($attributes_data) $current[$tag . '_attr'] = $attributes_data;
        $repeated_tag_index[$tag . '_' . $level] = 1;
        $current = &$current[$tag];
      } else { // There was another element with the same tag name
        if (isset($current[$tag][0])) { // If there is a 0th element it is already an array
          $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
          $repeated_tag_index[$tag . '_' . $level]++;
        } else { // This section will make the value an array if multiple tags with the same name appear together
          $current[$tag] = array($current[$tag], $result); //This will combine the existing item and the new item together to make an array 
          $repeated_tag_index[$tag . '_' . $level] = 2;
          if (isset($current[$tag . '_attr'])) { // The attribute of the last(0th) tag must be moved as well
            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
            unset($current[$tag . '_attr']);
          } 
        } 
        $last_item_index = $repeated_tag_index[$tag . '_' . $level]-1;
        $current = &$current[$tag][$last_item_index];
      } 
    } elseif ($type == "complete") { // Tags that ends in 1 line '<tag />'
      // See if the key is already taken.
      if (!isset($current[$tag])) { // New Key
        $current[$tag] = $result;
        $repeated_tag_index[$tag . '_' . $level] = 1;
        if ($priority == 'tag' and $attributes_data) $current[$tag . '_attr'] = $attributes_data;
      } else { // If taken, put all things inside a list(array)
        if (isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
          // ...push the new element into that array.
          $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
          if ($priority == 'tag' and $get_attributes and $attributes_data) {
            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
          } 
          $repeated_tag_index[$tag . '_' . $level]++;
        } else { // If it is not an array...
          $current[$tag] = array($current[$tag], $result); //...Make it an array using using the existing value and the new value 
          $repeated_tag_index[$tag . '_' . $level] = 1;
          if ($priority == 'tag' and $get_attributes) {
            if (isset($current[$tag . '_attr'])) { // The attribute of the last(0th) tag must be moved as well
              $current[$tag]['0_attr'] = $current[$tag . '_attr'];
              unset($current[$tag . '_attr']);
            } 
            if ($attributes_data) {
              $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
            } 
          } 
          $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken 
        } 
      } 
    } elseif ($type == 'close') { // End of tag '</tag>'
      $current = &$parent[$level-1];
    } 
  } 
  return($xml_array);
} 
// Array to XML
class array2xml {
  public $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
\n"; public $sub_item = array(); public function __construct($array) { $sub_item = array(); $this->output .= $this->xmlmake($array); } public function xmlmake($array, $fk = '') { $xml = ''; global $sub_item; foreach ($array as $key => $value) { if (is_array($value)) { if (is_numeric($key)) { $this->sub_item=array_merge($this->sub_item,array($fk)); $xml .= "<{$fk}>" . $this->xmlmake($value, $key) . "{$fk}>"; } else { $xml .= "<{$key}>" . $this->xmlmake($value, $key) . "{$key}>"; } } else { $xml .= "<{$key}>{$value}{$key}>\n"; } } return $xml; } public function output(){ foreach($this->sub_item as $t){ $this->output = str_replace("<{$t}><{$t}>","<{$t}>",$this->output); $this->output = str_replace("{$t}>{$t}>","{$t}>",$this->output); } return $this->output; } }

期望上述提供的代码方案能对各位在进行PHP程序设计时带来实质性的帮助。

上一篇
PHP 字符串操作核心功能与函数详解

PHP作为弱类型语言,支持数据自动转换为字符串进行运算。本文详解字符串定义中双引号与单引号的差异,对比echo与print的输出特性及文档句法用法。涵盖字符串连接、长度计算(含多字节处理)、分隔与裁剪、大小写转换等基础操作。深入解析strcmp等比较函数的行为陷阱,str_replace的多对一替换逻辑,以及strstr查找、HTML实体转换和md5加密等常用功能。

下一篇
PHP使用cURL访问HTTPS的完整示例与SSL验证详解

本文介绍在PHP中通过cURL发起HTTPS POST请求的方法,重点解析CURLOPT_SSL_VERIFYPEER、CURLOPT_CAINFO和CURLOPT_SSL_VERIFYHOST等关键参数的作用。文章区分了信任正规CA颁发证书与跳过验证两种场景的配置差异,并提供了Mozilla源生成的cacert.pem文件下载链接及处理POST数据过长的技巧。

相关文章

更多
PHP数组转XML工具库array2xml使用与改进

本文介绍在PHP中利用第三方库array2xml将数组高效转换为XML格式的方法,特别针对百度、360等搜索引擎Sitemap需求。文章详细解析了库的语法约定(如#表示CDATA、@表示属性),并分享了修复根节点CDATA冲突及支持CDATA与属性共存的代码改进经验。

2026.03.14 737
PHP中XML与数组互转的实用方法

在PHP后台开发中,经常需要处理前端传来的XML数据并返回XML格式响应,此时XML与关联数组的相互转化尤为频繁。本文提供了两个自定义函数:array2xml用于将简单数组转换为XML字符串,支持嵌套结构;xml2array则利用SimpleXML将XML字符串解析为关联数组。这两个方法简化了Flex等客户端与服务器的数据交互流程,提高了开发效率。

2026.09.06 637
PHP将XML对象转换为数组的方法详解

在PHP开发中,直接操作SimpleXMLElement对象往往不符合习惯。本文介绍如何使用(array)强制类型转换将XML对象转为数组。通过遍历对象属性并应用转换,可将嵌套的XML结构扁平化为易于处理的二维数组,从而简化数据提取逻辑。

2025.02.24 547
PHP实现XML与数组相互转换的代码示例

本文介绍在PHP中实现XML数据与数组结构相互转换的具体方法。通过自定义递归函数arrtoxml可将关联数组生成标准XML文档,利用simplexml_load_string结合json_encode/json_decode可实现XML字符串到多维数组的快速解析。文中附带了完整的函数代码及在线工具推荐,适用于需要处理配置数据或接口交互的场景。

2026.09.29 443
PHP Array2xml类实现数组转XML实例

本文介绍一种在PHP中将数组转换为XML格式的实现方法,通过Array2xml类完成数据结构的序列化。该方案适用于需要将内存中的数组对象持久化为XML文档的场景,帮助开发者快速处理数据交换需求。

2026.04.24 194
PHP将XML转换为数组的实现方法与工具

本文介绍PHP中将XML数据转换为数组的具体实现方法,通过递归函数解析XML节点并构建关联数组结构。文中提供了完整的核心代码逻辑及运行结果展示,帮助开发者理解数据结构映射过程。此外,还推荐了实用的在线XML与JSON互转及格式化压缩工具,便于日常开发中的快速调试与格式校验。

2026.06.19 117

专题推荐

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

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

PHP 定时任务配置与运行

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

Yii2 队列配置与常驻运行

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

PHP Session 过期时间设置方法

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

PHP URL 编码和解码方法

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

在线工具箱

更多
键码查询
键码查询

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

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

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

进制转换
进制转换

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

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。