SimpleXML属性到数组
有没有更优雅的方法来将SimpleXML属性转义为数组?SimpleXML属性到数组
$result = $xml->xpath($xpath);
$element = $result[ 0 ];
$attributes = (array) $element->attributes();
$attributes = $attributes[ '@attributes' ];
我真的不想循环它只是为了提取键/值对。我需要的只是把它放到一个数组中,然后传递给它。我会认为attributes()
会默认完成它,或者至少给出选项。但我甚至无法在任何地方找到上述解决方案,所以我不得不自己弄清楚。我是否过分复杂化了这个或者什么?
编辑:
现在我还用上面的脚本,直到我肯定知道是否访问@属性数组是安全与否。
不要直接阅读'@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"
如果你希望它是一个“真正的”数组,你得循环:
$attrArray = array();
$attr = $x->test[0]->a[0]->attributes();
foreach($attr as $key=>$val){
$attrArray[(string)$key] = (string)$val;
}
我想你会通过有循环。一旦你读到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') ....
}
什么是'objectsIntoArray'?另外,你不应该直接读'@ attributes',这就是' - > attributes()'的用处。 – 2012-07-11 19:49:40
对不起,我从我的代码中删除了刚刚编辑它的顶部部分。 – PoX 2012-07-11 20:24:47
更优雅的方式;它可以让你在不使用$属性[ '@属性']相同的结果:
$attributes = current($element->attributes());
绝对简单,紧凑,操作少。 – 2013-10-17 00:59:53
@silverskater:非常有用,它适合我!非常感谢 – 2013-12-23 07:06:28
这应该是答案 – kfriend 2014-12-15 15:42:29
你可以将整个XML文档转换成一个数组:
$array = json_decode(json_encode((array) simplexml_load_string("<response>{$xml}</response>")), true);
欲了解更多信息,请参见:https://github.com/gaarf/XML-string-to-PHP-array
是的,但问题在于它仍然认为自己是SimpleXML元素,因此您必须将'$ attr ['a']'转换为字符串才能正常工作。我将这个数组传递给另一个不知道它应该是什么类型的类,只是它需要是一个数组。 – mseancole 2012-07-11 19:39:15
啊,你在编辑中得到它...循环比我目前做的更好吗?我会认为这样做没有循环会更快。 – mseancole 2012-07-11 19:42:40
@showerhead:我不知道这是否更好,但我总是学会不要直接阅读“@属性”属性。 – 2012-07-11 19:53:22