zoukankan      html  css  js  c++  java
  • xml格式数据转数组的函数

    方法一:

    function xmlToArray($xml){
     
     //禁止引用外部xml实体
     
    libxml_disable_entity_loader(true);
     
    $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
     
    $val = json_decode(json_encode($xmlstring),true);
     
    return $val;
     
    }

    方法二:

    function xmlstr_to_array($xmlstr) {
            $doc = new DOMDocument();
            $doc->loadXML($xmlstr);
            return domnode_to_array($doc->documentElement);
        }
     function domnode_to_array($node) {
            $output = array();
            switch ($node->nodeType) {
                case XML_CDATA_SECTION_NODE:
                case XML_TEXT_NODE:
                    $output = trim($node->textContent);
                    break;
                case XML_ELEMENT_NODE:
                    for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {
                        $child = $node->childNodes->item($i);
                        $v = domnode_to_array($child);
                        if(isset($child->tagName)) {
                            $t = $child->tagName;
                            if(!isset($output[$t])) {
                                $output[$t] = array();
                            }
                            $output[$t][] = $v;
                        }
                        elseif($v) {
                            $output = (string) $v;
                        }
                    }
                    if(is_array($output)) {
                        if($node->attributes->length) {
                            $a = array();
                            foreach($node->attributes as $attrName => $attrNode) {
                                $a[$attrName] = (string) $attrNode->value;
                            }
                            $output['@attributes'] = $a;
                        }
                        foreach ($output as $t => $v) {
                            if(is_array($v) && count($v)==1 && $t!='@attributes') {
                                $output[$t] = $v[0];
                            }
                        }
                    }
                    break;
            }
            return $output;
        }

  • 相关阅读:
    [转载]Delphi 2009 (Tiburon) 新特性之 Exit 函数的新用法
    [转载][转]Delphi 2009 泛型+闭包能带来什么?
    [转载]现有 Delphi 项目迁移到 Tiburon 中的注意事项 (中)
    [转载]现有 Delphi 项目迁移到 Tiburon 中的注意事项 (上)
    [转载]现有 Delphi 项目迁移到 Tiburon 中的注意事项 (下)
    [转载]Delphi 2009 (Tiburon) 新特性之 Unicode 支持!
    [转载]Tiburon 支持 Unicode 的 LoadFromFile, SaveToFile
    GdiPlus[37]: IGPGraphicsPath (四) 路径变换
    GdiPlus[36]: IGPGraphicsPath (三) 路径中的数据
    GdiPlus[43]: IGPGraphics (二) 关于文本绘制
  • 原文地址:https://www.cnblogs.com/dai-/p/6754722.html
Copyright © 2011-2022 走看看