将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 ...
随机推荐
- CF-1093 (2019/02/10)
CF-1093 1093A - Dice Rolling 输出x/2即可 #include<bits/stdc++.h> using namespace std; int main() { ...
- PHP实现同array_column一样的功能
不用PHP自带的array_column函数实现同样的功能 <?php /** * Created by PhpStorm. * User: 123456 * Date: 2018/9/25 * ...
- cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
参考 http://blog.csdn.net/mazicwong/article/details/54946952 1.到https://curl.haxx.se/ca/cacert.pem复制下 ...
- css3属性:美化表单、点击元素产生的背景与边框怎么去掉,滚动回弹效果
- Java-basic-6-方法
命令行参数的使用 public class test { public static void main(String args[]) { for(int i = 0; i < args.len ...
- XML映射文件中关系映射
映射(多)对一.(一)对一的关联关系 1).使用列的别名 ①.若不关联数据表,则可以得到关联对象的id属性 ②.若还希望得到关联对象的其它属性.则必须关联其它的数据表 1.创建表: 员工表: DROP ...
- 查看 EGLIBC 版本
$ ldd --versionldd (Debian EGLIBC 2.13-38+deb7u1) 2.13
- BZOJ 3257: 树的难题
树形DP #include<cstdio> #include<algorithm> #define rep(i,x,y) for (int i=x; i<=y; i++) ...
- LA 3667 Ruler 搜索
题意: 给出\(n\)个长度,要设计一个有\(m\)个刻度的刻度尺,刻度尺的刻度从\(0\)开始. 使得任意一个长度都能被该刻度尺度量出来. 首先要使\(m\)最小,在\(m\)最小的前提下尺子的长度 ...
- JBuilder生成Exe
首先保证工程可以通过绿箭头执行 然后在File菜单中选择New,先建立Archive下的Application 接下来的界面中大部分可以直接选择“Next”,除了下面的第3步,会询问是否需要将工程引用 ...