php - How to do a WHERE statement with XPath?
I am working with this XML. It's a string from an API response in my code, but I put it there for easy view.
You'll see it has a<TransactionArray>
node with multiple<Transaction>
nodes in it. Right now I'm doing this to grab the<TransactionID>
value out of the LAST node, regardless of how many there are.
$DOM = new DOMDocument();
$DOM->loadXML($string);
$XPath = new DOMXPath($DOM);
$XPath->registerNamespace("ns","urn:ebay:apis:eBLBaseComponents");
$eBayTransIDs = $XPath->query("/ns:GetItemTransactionsResponse/ns:TransactionArray/ns:Transaction/ns:TransactionID/text()");
$eBayTransIDsLength = $eBayTransIDs->length;
if($eBayTransIDsLength > 0)
$eBayTransID = $eBayTransIDs->item($eBayTransIDsLength - 1)->data;
else
$eBayTransID = '';
This works as expected, which in most cases would be the most recent order, but it's not perfect logic and could cause a problem if two people purchase at the same time. I need to be more precise.
Inside the<Transaction>
nodes you will see/ExternalTransaction/ExternalTransactionID
and I do have this value available in my code. I cannot figure out how to specify that with XPath, though.
Basically, what I need is to "grab the<Transaction>
node WHERE/ExternalTransaction/ExternalTransactionID = $txn_id"
Answer
Solution:
First, two general notes:
WHERE
clauses roughly map to predicates within[
and]
.Next then, to select the
Transaction
elements WHEREExternalTransaction/ExternalTransactionID = $txn_id
, use a concatenation of strings to form an XPath expression as follows:Update to add namespace prefixes and select string value of selected
ExternalTransactionID
: