What is the best php DOM 2 Array function?

前端 未结 1 1247
执念已碎
执念已碎 2020-12-10 22:49

I want to parse xml files, The best way I found is to use DOMDocument() class so far.

sample xml string:



        
1条回答
  •  生来不讨喜
    2020-12-10 23:46

    You can use this (based on: http://php.net/manual/en/book.dom.php#93717);

    function xml_to_array($root) {
        $result = array();
    
        if ($root->hasAttributes()) {
            $attrs = $root->attributes;
            foreach ($attrs as $attr) {
                $result['@attributes'][$attr->name] = $attr->value;
            }
        }
    
        if ($root->hasChildNodes()) {
            $children = $root->childNodes;
            if ($children->length == 1) {
                $child = $children->item(0);
                if ($child->nodeType == XML_TEXT_NODE) {
                    $result['_value'] = $child->nodeValue;
                    return count($result) == 1
                        ? $result['_value']
                        : $result;
                }
            }
            $groups = array();
            foreach ($children as $child) {
                if (!isset($result[$child->nodeName])) {
                    $result[$child->nodeName] = xml_to_array($child);
                } else {
                    if (!isset($groups[$child->nodeName])) {
                        $result[$child->nodeName] = array($result[$child->nodeName]);
                        $groups[$child->nodeName] = 1;
                    }
                    $result[$child->nodeName][] = xml_to_array($child);
                }
            }
        }
    
        return $result;
    }
    

    Test;

    $s = '
            
                
                    
                        
                        
                        
                        
                    
                
            ';
    
    $xml = new DOMDocument();
    $xml->loadXML($s);
    $xmlArray = xml_to_array($xml);
    print_r($xmlArray);
    // print_r($xmlArray['response']['resData']['contact:infData']['contact:status'][0]['@attributes']['s']);
    // foreach ($xmlArray['response']['resData']['contact:infData']['contact:status'] as $status) {
        // echo $status['@attributes']['s'] ."\n";
    // }
    

    0 讨论(0)
提交回复
热议问题