mse*_*ole 22 php arrays attributes simplexml
有没有更优雅的方法将SimpleXML属性转义为数组?
$result = $xml->xpath( $xpath );
$element = $result[ 0 ];
$attributes = (array) $element->attributes();
$attributes = $attributes[ '@attributes' ];
Run Code Online (Sandbox Code Playgroud)
我真的不想只是为了提取键/值对而循环它.我只需要将它放入一个数组然后传递它.我本以为attributes()
默认会这样做,或者至少给出了选项.但我甚至无法在任何地方找到上述解决方案,我必须自己解决这个问题.我是在复杂这个还是什么?
编辑:
我仍然使用上面的脚本,直到我确定访问@attributes数组是否安全.
小智 48
一种更优雅的方式; 它在不使用$ attributes ['@attributes']的情况下为您提供相同的结果:
$attributes = current($element->attributes());
Run Code Online (Sandbox Code Playgroud)
Roc*_*mat 11
不要直接阅读该'@attributes'
物业,这是供内部使用.无论如何,attributes()
已经可以用作数组而无需"转换"为真正的数组.
例如:
<?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"
Run Code Online (Sandbox Code Playgroud)
如果你想让它成为一个"真正的"数组,你将不得不循环:
$attrArray = array();
$attr = $x->test[0]->a[0]->attributes();
foreach($attr as $key=>$val){
$attrArray[(string)$key] = (string)$val;
}
Run Code Online (Sandbox Code Playgroud)