SimpleXML 属性到数组 [英] SimpleXML Attributes to Array
问题描述
是否有更优雅的方法将 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' ];
我真的不想为了提取键/值对而遍历它.我所需要的只是将它放入一个数组中,然后将其传递.我原以为 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 数组是否安全之前,我仍在使用上述脚本.
I'm still using the above script until I know for sure whether accessing the @attributes array is safe or not.
推荐答案
不要直接读取 '@attributes'
属性,这是供内部使用的.无论如何,attributes()
已经可以用作数组而无需转换"为真正的数组.
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屋!