SimpleXML的属性到数组 [英] SimpleXML Attributes to Array

查看:213
本文介绍了SimpleXML的属性到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有逃生的SimpleXML任何更优雅的方式属性到一个数组中?

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

$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?

编辑:

我还是用上面的脚本,直到我肯定知道是否访问@属性数组是安全与否。

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

推荐答案

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

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.

例如:

<?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;
}

这篇关于SimpleXML的属性到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆