I have the following PHP and XML:
$XML = <<<XML
<items>
<item id="12">
<name>Item A</name>
</item>
<item id="34">
<name>Item B</name>
</item>
<item id="56">
<name>Item C</name>
</item>
</items>
XML;
$simpleXmlEle = new SimpleXMLElement($XML);
print_r($simpleXmlEle->xpath('./item[1]'));
print "- - - - - - -\n";
print_r($simpleXmlEle->xpath('./item[2][@id]'));
print "- - - - - - -\n";
print_r($simpleXmlEle->xpath('./item[1]/name'));
I am able to access the ID like this
$simpleXmlEle->items->item[0]['id']
As it is a dynamic application the xpath is provided at runtime as a string so I believe I should use xpath.
The above PHP produces:
PHP:
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 12
)
[name] => Item A
)
)
- - - - - - -
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 34
)
[name] => Item B
)
)
- - - - - - -
Array
(
[0] => SimpleXMLElement Object
(
)
)
I understand the 1st output, but inside the 2nd output the whole element is being returned instead of just the attribute.
1) Any ideas why?
Also the last item is empty
2)why is this and what would be the right xpath?
I am aiming for 2nd and 3rd output as: 34 (value of id attribute of 2nd element) Item A (just name of 1st element).
See the below:
Prints:
Make sure you DO NOT do:
According to the documentation // returns ALL elements with this name, so if there is an item element on a deeper level then its value is returned too which is not be desired.
hope that helps