这里提供一个类来将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. 【线段树 扫描线 二维数点】loj#6276. 果树

    路径计数转成二维数点很妙啊 题目描述 NiroBC 姐姐是个活泼的少女,她十分喜欢爬树,而她家门口正好有一棵果树,正好满足了她爬树的需求. 这颗果树有 $N$ 个节点,标号 $1 \ldots N$ ...

  2. Docker 容器的网络连接 & 容器互联

    1. Docker 容器网络基础架构 Docker0 ifconfig查看到的 docker0 是linux的虚拟网桥(OSI数据链路层) docker0 地址划分: 172.17.42.1 255. ...

  3. python中打印金字塔和九九乘法表的几种方法

    # 打印九九乘法表for i in range(1,10): for j in range(1,i+1): # x=i*j # print(i,'*',j,'=',x,end=' ') print(' ...

  4. Hard problem CodeForces - 706C

    Time limit1000 ms Memory limit262144 kB 题目: Vasiliy is fond of solving different tasks. Today he fou ...

  5. hdu-1338 game predictions(贪心题)

    Suppose there are M people, including you, playing a special card game. At the beginning, each playe ...

  6. Linux: 正则表达式

    正则表达式:正规的表示法,常规的表示法(Regular Expression)正则表达式使用单个字符串来描述,匹配一系列的符合某个句发规则的字符串. 1)命令格式; grep  [正则] 字符串 文件 ...

  7. ubuntu12.04 ppa安装git

    PPA地址:https://launchpad.net/~git-core/+archive/ppa 支持所有的Ubuntu版本. 运行命令: sudo apt-add-repository ppa: ...

  8. Phonegap环境配置和安装插件

    一:安装好jdk(配置好环境变量) 二:安装好Android SDK(配置好环境变量path F:\Android\android-sdk-windows\platform-tools;F:\Andr ...

  9. 程序员必需知道的windows快捷键

    系统操作的快捷键 1.F5------刷新 2.window+E------打开我的电脑 3.window+r------打开运行 4.window+l------快速锁机 5.window+d--- ...

  10. Leetcode33--->Search in Rotated Sorted Array(在旋转数组中找出给定的target值的位置)

    题目: 给定一个旋转数组,但是你不知道旋转位置,在旋转数组中找出给定target值出现的位置:你可以假设在数组中没有重复值出现 举例: (i.e., 0 1 2 4 5 6 7 might becom ...