php SimpleXML 属性到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11439829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:31:10  来源:igfitidea点击:

SimpleXML Attributes to Array

phparraysattributessimplexml

提问by mseancole

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

有没有更优雅的方法将 SimpleXML 属性转义到数组?

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

I don't really want to have to loop through it just to extract the key/value pair. All I need is to get it into an array and then pass it on. I would have thought attributes()would have done it by default, or at least given the option. But I couldn't even find the above solution anywhere, I had to figure that out on my own. Am I over complicating this or something?

我真的不想为了提取键/值对而遍历它。我所需要的只是将它放入一个数组中,然后将其传递。我原以为attributes()默认情况下会这样做,或者至少可以选择。但是我什至无法在任何地方找到上述解决方案,我不得不自己解决这个问题。我是不是把这件事复杂化了?

Edit:

编辑:

I'm still using the above script until I know for sure whether accessing the @attributes array is safe or not.

我仍在使用上述脚本,直到我确定访问 @attributes 数组是否安全为止。

采纳答案by Rocket Hazmat

Don't directly read the '@attributes'property, that's for internal use. Anyway, attributes()can already be used as an array without needing to "convert" to a real array.

不要直接读取'@attributes'属性,这是供内部使用的。无论如何,attributes()已经可以用作数组而无需“转换”为真正的数组。

For example:

例如:

<?php
$xml = '<xml><test><a a="b" r="x" q="v" /></test><b/></xml>';
$x = new SimpleXMLElement($xml);

$attr = $x->test[0]->a[0]->attributes();
echo $attr['a']; // "b"

If you want it to be a "true" array, you're gonna have to loop:

如果你希望它是一个“真正的”数组,你将不得不循环:

$attrArray = array();
$attr = $x->test[0]->a[0]->attributes();

foreach($attr as $key=>$val){
    $attrArray[(string)$key] = (string)$val;
}

回答by silverskater

a more elegant way; it gives you the same results without using $attributes[ '@attributes' ]:

更优雅的方式;它在不使用$attributes[ '@attributes' ] 的情况下为您提供相同的结果:

$attributes = current($element->attributes());

回答by Kus

You could convert the whole xml document into an array:

您可以将整个 xml 文档转换为一个数组:

$array = json_decode(json_encode((array) simplexml_load_string("<response>{$xml}</response>")), true);

For more information see: https://github.com/gaarf/XML-string-to-PHP-array

有关更多信息,请参阅:https: //github.com/gaarf/XML-string-to-PHP-array

回答by Manik Thakur

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.

这也为我提供了所有属性,这是我没有从任何其他方法中获得的。

回答by PoX

I think you will have to loop through. You can get it into array once you read xml.

我想你将不得不循环。读取xml后,您可以将其放入数组。

<?php
function objectsIntoArray($arrObjData, $arrSkipIndices = array())
{
$arrData = array();

// if input is object, convert into array
if (is_object($arrObjData)) {
    $arrObjData = get_object_vars($arrObjData);
}

if (is_array($arrObjData)) {
    foreach ($arrObjData as $index => $value) {
        if (is_object($value) || is_array($value)) {
            $value = objectsIntoArray($value, $arrSkipIndices); // recursive call
        }
        if (in_array($index, $arrSkipIndices)) {
            continue;
        }
        $arrData[$index] = $value;
    }
}
return $arrData;
}

$xmlStr = file_get_contents($xml_file);
$xmlObj = simplexml_load_string($xmlStr);
$arrXml = objectsIntoArray($xmlObj);

foreach($arrXml as $attr)
  foreach($attr as $key->$val){
 if($key == '@attributes') ....
}