将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;    }}?>
时间: 2025-01-04 18:50:02

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

php解析xml,并将xml转换为层级数组

1)xml_parser_create([ string $encoding ] ):建立一个新的xml解析器并返回可被其他xml函数使用的资源句柄, 参数$encoding: php4,中用来只指定要被解析的xml输入的字符编码方式: php5,自动侦测输入xml的编码,encoding仅用来指定解析后输出数据的编码 默认:输入编码=输出编码 php5.0.2+默认编码utf-8:之前版本,ISO-8859-1 2)bool xml_parser_set_option(resource $pa

PHP XML To Array将XML转换为数组

1 // Xml 转 数组, 包括根键,忽略空元素和属性,尚有重大错误 2 function xml_to_array( $xml ) 3 { 4 $reg = "/<(\\w+)[^>]*?>([\\x00-\\xFF]*?)<\\/\\1>/"; 5 if(preg_match_all($reg, $xml, $matches)) 6 { 7 $count = count($matches[0]); 8 $arr = array(); 9 for($i

php xml操作类DOMDocument xml转化为数组的函数

/** * node2array函数,将xml转换为数组 * @param object $node */ public function node2array($node){ $array = false; if ($node->hasAttributes()){ foreach ($node->attributes as $attr){ $array[$attr->nodeName] = $attr->nodeValue; } } if ($node->hasChildN

PHP中simpleXML递归实现XML文件与数组的相互转化(原创)

一.XML文件转换为数组<?php /*******************************************************/ //simpleXML  解析XML文件非常简单 //因为它一次性把XML文件解析成一个大对象 //来个简单的实例 /************************************************ //从文件载入XML文档 //$simxml  =  simplexml_load_file('book.xml'); //prin

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

/// <summary> /// 16进制字符转换为byte数组 /// </summary> /// <param name="hexString">偶数位,由16进制字符[0-9a-fA-F]组成</param> /// <returns>null为转换失败</returns> private byte[] HexStringToBytes(string hexString) { if (string.IsN

[Arduino] 在串口读取多个字符串,并且转换为数字数组

功能如题目.在串口收到逗号分割的6串数字比如100,200,45,4,87,99然后在6个PWM端口3, 5, 6, 9, 10, 11输出对应PWM值代码注释很详细了,就不再说明了. //定义一个comdata字符串变量,赋初值为空值 String comdata = ""; //numdata是分拆之后的数字数组 int numdata[6] = {0}, PWMPin[6] = {3, 5, 6, 9, 10, 11}, mark = 0; void setup() { //定义

XML转换为Map通用算法实现(Stax实现)

目前项目中需要将XML转换为Map,下面给出了自己的代码实现.请各路大神提供更好的代码实现. 场景: 在项目中需要解析XML文本字符串,需要将XML文本字符串映射为Map格式的对象. 需求: 1.为了提高性能,需要使用Stax进行解析 2.Map结构内部需要支持List.Map.String三种数据格式 示例: 例一: * 字符串:<name>BurceLiu</name><age>18</age> * 转换为的Map结构:{age=18, name=Bur

XML转换成数组方法

<?php function xmlToArray2($xml) { // 将XML转为array $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $array_data; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transition

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

原文:分享一个解析XML成为php数组的方法 <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ $xml = 'site_1.xml'; $myxml = simplexml_load_file($xml); // print_r($myxml); print_r(xmlToArray($myxml)); function xmlToArra