iterating SimpleXml xpath result

蹲街弑〆低调 提交于 2019-12-06 11:53:22

As was mentionned in Sjoerd's answer, $block is not an array. SimpleXMLElement::xpath() returns an array of objects, each of those objects representing one single element. So basically, you have to replace $block[0] with $block since it already represents the block you're looking for.

Also, I have rewritten your XPath expression. Since you're looking for a <data:Block/> element, that's what you should target. The thing about <data:Code/> is a predicate, so it should go within brackets. Of course in your case the result is the same, but it's good practice to have semantically correct expressions, helps having a clearer idea of what's going on later on when you re-read that code (or if someone else has to maintain it.)

foreach ($xml->xpath('//data:Block[data:Code="Fbf"]') as $block) {
    foreach ($block->Fields->Field as $field) {
        echo "Code: ". $field->Code ."\n"; // SHould return FinnsIFbf
    }
}

Update

I didn't notice that you said that all you were interested in was the <Field/> element. In that case you can get it directly through XPath: (remember that they're all in the data namespace)

foreach ($xml->xpath('//data:Block[data:Code="Fbf"]/data:Fields/data:Field') as $field) {
    echo "Code: ". $field->Code ."\n"; // SHould return FinnsIFbf
}

It is probably because $block is not an array. You should use var_dump or print_r to confirm that, and then use is_array in your code to make sure it is an array.

If SimpleXML finds multiple elements with the same name, it returns an array of objects. If it finds a single element, it returns just that element, not an array with a single element. So when you expect multiple elements, you always have to code an exception case for when there is only one element.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!