php - How to do a WHERE statement with XPath?

540

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"

251

Answer

Solution:

First, two general notes:

  • WHERE clauses roughly map to predicates within[ and].
  • To inject an external variable value into the XPath, you can construct it from separate strings concatenated together.

Next then, to select theTransaction elements WHEREExternalTransaction/ExternalTransactionID = $txn_id, use a concatenation of strings to form an XPath expression as follows:

"//Transaction[ExternalTransaction/ExternalTransactionID = '" + $txn_id + "']"

Update to add namespace prefixes and select string value of selectedExternalTransactionID:

"string(//ns:Transaction[ns:ExternalTransaction/ns:ExternalTransactionID = '" 
        + $txn_id 
        + "'])"

People are also looking for solutions to the problem: php - Search into multidimensional stdClass Object

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.