Here is my code:
$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);
print_r($objSimpleXML->xpath('./item[1]'));
print "- - - - - - -\n";
print_r($objSimpleXML->xpath('./item[2][@id]'));
print "- - - - - - -\n";
print_r($objSimpleXML->xpath('./item[1]/name'));
Nothing really special: I am trying to extract some data via XPath
. The path must be a string to design a dynamic program which loads its data from a XML
configuration file.
When using PHP object access like $objSimpleXML->items->item[0]['id']
everything works fine. But XPath
approach does not really work. The code above generates the following output:
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 123
)
[name] => Item 1
)
)
- - - - - - -
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 456
)
[name] => Item 2
)
)
- - - - - - -
Array
(
[0] => SimpleXMLElement Object
(
)
)
I agree with the first output. But in the second output the whole element is returned instead of the attribute. Why? And the last listing is empty instead of name content?