这里提供一个类来将XML转换为PHP数组,下面是类的代码

<?php
/**
* XML2Array: A class to convert XML to array in PHP
* It returns the array which can be converted back to XML using the Array2XML script
* It takes an XML string or a DOMDocument object as an input.
*
* See Array2XML: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes
*
* Author : Lalit Patel
* Website: http://www.lalit.org/lab/convert-xml-to-array-in-php-xml2array
* License: Apache License 2.0
* http://www.apache.org/licenses/LICENSE-2.0
* Version: 0.1 (07 Dec 2011)
* Version: 0.2 (04 Mar 2012)
* Fixed typo 'DomDocument' to 'DOMDocument'
*
* Usage:
* $array = XML2Array::createArray($xml);
*/ class XML2Array { private static $xml = null;
private static $encoding = 'UTF-8'; /**
* Initialize the root XML node [optional]
* @param $version
* @param $encoding
* @param $format_output
*/
public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) {
self::$xml = new DOMDocument($version, $encoding);
self::$xml->formatOutput = $format_output;
self::$encoding = $encoding;
} /**
* Convert an XML to Array
* @param string $node_name - name of the root node to be converted
* @param array $arr - aray to be converterd
* @return DOMDocument
*/
public static function &createArray($input_xml) {
$xml = self::getXMLRoot();
if(is_string($input_xml)) {
$parsed = $xml->loadXML($input_xml);
if(!$parsed) {
throw new Exception('[XML2Array] Error parsing the XML string.');
}
} else {
if(get_class($input_xml) != 'DOMDocument') {
throw new Exception('[XML2Array] The input XML object should be of type: DOMDocument.');
}
$xml = self::$xml = $input_xml;
}
$array[$xml->documentElement->tagName] = self::convert($xml->documentElement);
self::$xml = null; // clear the xml node in the class for 2nd time use.
return $array;
} /**
* Convert an Array to XML
* @param mixed $node - XML as a string or as an object of DOMDocument
* @return mixed
*/
private static function &convert($node) {
$output = array(); switch ($node->nodeType) {
case XML_CDATA_SECTION_NODE:
$output['@cdata'] = trim($node->textContent);
break; case XML_TEXT_NODE:
$output = trim($node->textContent);
break; case XML_ELEMENT_NODE: // for each child node, call the covert function recursively
for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {
$child = $node->childNodes->item($i);
$v = self::convert($child);
if(isset($child->tagName)) {
$t = $child->tagName; // assume more nodes of same kind are coming
if(!isset($output[$t])) {
$output[$t] = array();
}
$output[$t][] = $v;
} else {
//check if it is not an empty text node
if($v !== '') {
$output = $v;
}
}
} if(is_array($output)) {
// if only one node of its kind, assign it directly instead if array($value);
foreach ($output as $t => $v) {
if(is_array($v) && count($v)==1) {
$output[$t] = $v[0];
}
}
if(empty($output)) {
//for empty nodes
$output = '';
}
} // loop through the attributes and collect them
if($node->attributes->length) {
$a = array();
foreach($node->attributes as $attrName => $attrNode) {
$a[$attrName] = (string) $attrNode->value;
}
// if its an leaf node, store the value in @value instead of directly storing it.
if(!is_array($output)) {
$output = array('@value' => $output);
}
$output['@attributes'] = $a;
}
break;
}
return $output;
} /*
* Get the root XML node, if there isn't one, create it.
*/
private static function getXMLRoot(){
if(empty(self::$xml)) {
self::init();
}
return self::$xml;
}
}
?>

将xml转换为PHP数组的更多相关文章

  1. XML转换为对象操作类详解

    //XML转换为对象操作类 //一,XML与Object转换类 using System.IO; using System.Runtime.Serialization.Formatters.Binar ...

  2. XML转换为Map通用算法实现 Java版本(Stax实现)

    目前项目中需要将XML转换为Map,下面给出了自己的代码实现. 后续将为大家提供Dom版本的实现. 请各路大神给予各种优良实现. 场景: 在项目中需要解析XML文本字符串,需要将XML文本字符串映射为 ...

  3. 网络流转换为Byte数组

    /// <summary> /// 网络流转换为Byte数组 /// </summary> /// <param name="stream">& ...

  4. 16进制字符串转换为byte数组

    /// <summary> /// 16进制字符转换为byte数组 /// </summary> /// <param name="hexString" ...

  5. 实战:sqlserver 2008 扩展事件-XML转换为标准的table格式

    --假设已经存在Event Session删除 IF EXISTS (SELECT * FROM sys.server_event_sessions WHERE name='MonitorLongQu ...

  6. 分享一个解析XML成为php数组的方法

    原文:分享一个解析XML成为php数组的方法 <?php /* * To change this template, choose Tools | Templates * and open th ...

  7. 数组转xml格式/xml格式转数组

    数组转xml格式 $arr=array( 'username'=>'huahua', 'password'=>'123456', 'number'=>'15889652911', ) ...

  8. XML转换成数组方法

    <?php function xmlToArray2($xml) { // 将XML转为array $array_data = json_decode(json_encode(simplexml ...

  9. php xml字符串转数组

    function xmltoarr($path){//xml字符串转数组 $xmlfile = file_get_contents($path);//提取xml文档中的内容以字符串格式赋给变量 $ob ...

随机推荐

  1. 基于matlab的蓝色车牌定位与识别---识别

    接着昨天的工作,把最后一部分识别讲完. 关于字符识别这块,一种最省事的办法是匹配识别,将所得的字符和自己的标准字符库相减,计算所得结果,值最小的即为识别的结果.不过这种方法是在所得字符较为标准的情况, ...

  2. 【Machine Learning is Fun!】1.The world’s easiest introduction to Machine Learning

    Bigger update: The content of this article is now available as a full-length video course that walks ...

  3. NOIP模拟赛 无线通讯网

    [题目描述] 国防部计划用无线网络连接若干个边防哨所.2种不同的通讯技术用来搭建无线网络:每个边防哨所都要配备无线电收发器:有一些哨所还可以增配卫星电话. 任意两个配备了一条卫星电话线路的哨所(两边都 ...

  4. php curl使用例子

    PHP支持的由Daniel Stenberg创建的libcurl库允许你与各种的服务器使用各种类型的协议进行连接和通讯.libcurl目前支持http.https.ftp.gopher.telnet. ...

  5. centos7.4系统部署nodejs前端项目

    1.安装nodejs运行环境 wget命令下载Node.js安装包,该安装包是编译好的文件,解压之后,在bin文件夹中就已存在node和npm,无需重复编译 wget https://nodejs.o ...

  6. GoF23种设计模式之行为型模式之状态模式

    一.概述         定义对象之间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新. 二.适用性 1.一个对象的行为取决于它的状态,并且它必须在运行时刻 ...

  7. hdu-2063 过山车(二分图)

    Time limit1000 ms Memory limit32768 kB RPG girls今天和大家一起去游乐场玩,终于可以坐上梦寐以求的过山车了.可是,过山车的每一排只有两个座位,而且还有条不 ...

  8. LightOj:1422-Halloween Costumes

    传送门:http://www.lightoj.com/volume_showproblem.php?problem=1422 Halloween Costumes problem descriptio ...

  9. Linux学习-开机过程的问题解决

    忘记 root 密码的解决之道 新版的 systemd 的管理机制中,默认的 rescue 模式是无法直接取得 root 权限的喔!还是得要 使用 root 的密码才能够登入 rescure 环境.没 ...

  10. 远程连接MYSQL8.0服务器问题

    title: 远程连接MYSQL8.0服务器问题 date: 2018-07-07 11:02:26 updated: tags: [MYSQL,坑] description: keywords: c ...