SimpleXML属性到数组

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)

  • 绝对简单、紧凑和更少的操作。 (2认同)
  • 这应该是答案 (2认同)
  • 好的谢谢!我通常添加 `current(...) ?: []` 因为如果 XML 元素没有属性,`current(...)` 返回 `false`,其中空数组(恕我直言)更合适。 (2认同)

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)

  • 是的,但问题在于它仍然认为自己是一个 SimpleXML 元素,因此您必须将 `$attr[ 'a' ]` 类型转换为字符串才能正常工作。我将这个数组传递给另一个不知道它应该是什么类型的类,只知道它需要是一个数组。 (2认同)