How do you run an Xpath query on the current SimpleXMLElement object inside a for loop. For example
<?php
$xml = simplexml_load_string('<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</bookstore> ');
foreach ($xml as $value) {
$result = $value->xpath('//title');
var_dump($result);
break;
}
?>
array
0 =>
object(SimpleXMLElement)[189]
public '@attributes' =>
array
'lang' => string 'eng' (length=3)
string 'Harry Potter' (length=12)
1 =>
object(SimpleXMLElement)[188]
public '@attributes' =>
array
'lang' => string 'eng' (length=3)
string 'Learning XML' (length=12)
This outputs the results of both book elements whereas it is my intent to only show the first. I am attempting for the query to run only on the $value object in the for loop as I may want to run different queries on each book (So it must be in a loop!) Not on every single book which is what it is currently doing.
// Selects nodes in the document from the current node that match the selection no matter where they are.
I was already in the required node (e.g. $value) when I ran a query to select all nodes from the root, therefore gaining info from all nodes.
Since I am already in the required node element removal the // obtains the expected result, running the query on the current node.