将xml转换为PHP数组
这里提供一个类来将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数组的更多相关文章
- XML转换为对象操作类详解
//XML转换为对象操作类 //一,XML与Object转换类 using System.IO; using System.Runtime.Serialization.Formatters.Binar ...
- XML转换为Map通用算法实现 Java版本(Stax实现)
目前项目中需要将XML转换为Map,下面给出了自己的代码实现. 后续将为大家提供Dom版本的实现. 请各路大神给予各种优良实现. 场景: 在项目中需要解析XML文本字符串,需要将XML文本字符串映射为 ...
- 网络流转换为Byte数组
/// <summary> /// 网络流转换为Byte数组 /// </summary> /// <param name="stream">& ...
- 16进制字符串转换为byte数组
/// <summary> /// 16进制字符转换为byte数组 /// </summary> /// <param name="hexString" ...
- 实战:sqlserver 2008 扩展事件-XML转换为标准的table格式
--假设已经存在Event Session删除 IF EXISTS (SELECT * FROM sys.server_event_sessions WHERE name='MonitorLongQu ...
- 分享一个解析XML成为php数组的方法
原文:分享一个解析XML成为php数组的方法 <?php /* * To change this template, choose Tools | Templates * and open th ...
- 数组转xml格式/xml格式转数组
数组转xml格式 $arr=array( 'username'=>'huahua', 'password'=>'123456', 'number'=>'15889652911', ) ...
- XML转换成数组方法
<?php function xmlToArray2($xml) { // 将XML转为array $array_data = json_decode(json_encode(simplexml ...
- php xml字符串转数组
function xmltoarr($path){//xml字符串转数组 $xmlfile = file_get_contents($path);//提取xml文档中的内容以字符串格式赋给变量 $ob ...
随机推荐
- 【贪心 哈夫曼树】bzoj2923: [Poi1998]The lightest language
失去了以前用STL乱搞的能力…… 题目描述 语言也是数学上经常研究的一种数据. 给出数学上关于语言的如下定义: 字母表:大小为 K 的字母表是一个由 K 不同的字符组成的集合. 单词:长度为 m 的单 ...
- pm2日志记录和日志分割
pm2日志记录和日志分割 pm2介绍 pm2是nodejs进程管理工具,现在基本是node生产服务器的标准选择,可以帮助我们实现node多进程服务,开启的多个实例自动实现负载均衡. 最重要的是保证no ...
- 每天一个linux命令(13):less命令
less 工具也是对文件或其它输出进行分页显示的工具,应该说是linux正统查看文件内容的工具,功能极其强大.less 的用法比起 more 更加的有弹性.在 more 的时候,我们并没有办法向前面翻 ...
- unbuntu14下Qt4.8 和MySQL连接问题 QSqlDatabase: QMYSQL driver not loaded QSqlDatabase: available drivers: QSQLITE
使用 QSqlDatabase::addDatabase创建数据库时 会报错: QSqlDatabase: QMYSQL driver not loaded QSqlDatabase: availab ...
- python入门:in 的用法(它在不在这个字符串里面)
#!/usr/bin/env python # -*- coding:utf-8 -*- #in 的用法(它在不在这个字符串里面) #ret(返回,译音:ruai特) #给s赋值为字符串“Alex S ...
- leetcode-23-DynamicProgramming-1
357. Count Numbers with Unique Digits 解题思路: 用arr[i]存放长度为i时,各位互不相同的数字的个数,所以arr[1]=10,arr[2]=9*9.(第一位要 ...
- Java-basic-4-数据类型
Number类 装箱:将内置数据类型作为包装类对象使用:拆箱:相反 public class test{ public static void main(String args[]) { // box ...
- The 2018 ACM-ICPC China JiangSu Provincial Programming Contest I. T-shirt
JSZKC is going to spend his vacation! His vacation has N days. Each day, he can choose a T-shirt to ...
- java事物
[引用:http://www.cnblogs.com/kristain/articles/2038397.html] 一.什么是事务 事务是访问数据库的一个操作序列,数据库应用系统通过事务集来完成对数 ...
- 大数据学习——akka自定义RPC
实现 package cn.itcast.akka import akka.actor.{Actor, ActorSystem, Props} import akka.actor.Actor.Rece ...