-3

Possible Duplicate:
A simple program to CRUD node and node values of xml file
XPath and PHP: nothing works properly

$XML = <<<XML
<items>
    <item id="123">
        <name>Item 1</name>
    </item>
    <item id="456">
        <name>Item 2</name>
    </item>
    <item id="789">
        <name>Item 3</name>
    </item>
</items>
XML;

$objSimpleXML = new SimpleXMLElement($XML);

echo $objSimpleXML->item[2]->name; // output: Item 3 (OK)
echo '<br><pre>';
print_r($objSimpleXML->xpath('./item[1]/name')); // output: empty Array!!!

Hello! How to get "Item 3" as output using pure xpath query? (My proposal outputs an empty array.)

Community
  • 1
  • 1
ottom
  • 1
  • 1
  • 1
  • 2
    This looks suspiciously similar to http://stackoverflow.com/questions/14280450/xpath-and-php-nothing-works-properly/14280528#14280528. – Andrew Cheong Jan 12 '13 at 10:08

1 Answers1

1

This is because xpath collection indexes are 1-based opposed to our most familiar 0-based array.

To get Item 3 using pure xpath query is not possible as xpath function returns array. You have to store the result first and use array index to access the element.

$item = $objSimpleXML->xpath('./item[3]/name');
$str = $item[0];

From W3C's XPATH 1.0 spec, these are called predicate

An axis is either a forward axis or a reverse axis. An axis that only ever contains the context node or nodes that are after the context node in document order is a forward axis. An axis that only ever contains the context node or nodes that are before the context node in document order is a reverse axis. Thus, the ancestor, ancestor-or-self, preceding, and preceding-sibling axes are reverse axes; all other axes are forward axes. Since the self axis always contains at most one node, it makes no difference whether it is a forward or reverse axis. The proximity position of a member of a node-set with respect to an axis is defined to be the position of the node in the node-set ordered in document order if the axis is a forward axis and ordered in reverse document order if the axis is a reverse axis. The first position is 1.

Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187