Using xpath on PHP: how to select first child?

php, xml, xpath

Solution

As Felix said: What about trying?

$l = new SimpleXMLElement('<layout>
  <pattern> ... </pattern> 
  <row> ... </row>  
</layout>');
foreach($l->xpath('/layout/*[1]') as $n) {// yeah yeah, it's only one....
  echo $n->getName();
}

prints `pattern`. (php 5.3.1/win32/php.net build)

Problem

I have an XML structure like this one: ``` <layout> <pattern> ... </pattern> <row> ... </row> </layout> ``` How can I select the first node of `<layout>` by its index, using XPath? w3schools indicates syntax similar to `/bookstore/book[1]/title `, but then says: There is a problem with this. The example above shows different results in IE and other browsers. IE5 and later has implemented that [0] should be the first node, but according to the W3C standard it should have been [1]!! A Workaround! To solve the [0] and [1] problem in IE5+, you can set the SelectionLanguage to XPath. But that's client-specific. The PHP manual isn't very clear about this either.

Original source