SimpleXML Attributes to Array

前端 未结 5 1008
臣服心动
臣服心动 2020-12-15 05:19

Is there any more elegant way to escape SimpleXML attributes to an array?

$result = $xml->xpath( $xpath );
$element = $result[ 0 ];
$attributes = (array)          


        
5条回答
  •  北海茫月
    2020-12-15 05:45

    For me below method worked

    function xmlToArray(SimpleXMLElement $xml)
    {
        $parser = function (SimpleXMLElement $xml, array $collection = []) use (&$parser) {
            $nodes = $xml->children();
            $attributes = $xml->attributes();
    
            if (0 !== count($attributes)) {
                foreach ($attributes as $attrName => $attrValue) {
                    $collection['@attributes'][$attrName] = strval($attrValue);
                }
            }
    
            if (0 === $nodes->count()) {
                if($xml->attributes())
                {
                    $collection['value'] = strval($xml);
                }
                else
                {
                    $collection = strval($xml);
                }
                return $collection;
            }
    
            foreach ($nodes as $nodeName => $nodeValue) {
                if (count($nodeValue->xpath('../' . $nodeName)) < 2) {
                    $collection[$nodeName] = $parser($nodeValue);
                    continue;
                }
    
                $collection[$nodeName][] = $parser($nodeValue);
            }
    
            return $collection;
        };
    
        return [
            $xml->getName() => $parser($xml)
        ];
    }
    

    This also provides me all the attributes as well, which I didn't get from any other method.

提交回复
热议问题