In XPath, how can I get the node with the highest value? e.g.
<tr>
<td>$12.00</td>
<td>$24.00</td>
<td>$13.00</td>
</tr>
would return $24.00.
I'm using PHP DOM, so this would be XPath version 1.0.
I spend the last little while trying to come up with the most elegant solution for you. As you know, max ins't available in XPath 1.0. I've tried several different approach, most of which don't seem very efficient.
<?php
$doc = new DOMDocument;
$doc->loadXml('<table><tr><td>$12.00</td><td>$24.00</td><td>$13.00</td></tr></table>');
function dom_xpath_max($this, $nodes)
{
usort($nodes, create_function('$a, $b', 'return strcmp($b->textContent, $a->textContent);'));
return $this[0]->textContent == $nodes[0]->textContent;
}
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('php', 'http://php.net/xpath');
$xpath->registerPHPFunctions('dom_xpath_max');
$result = $xpath->evaluate('//table/tr/td[php:function("dom_xpath_max", ., ../td)]');
echo $result->item(0)->textContent;
?>
Alternatively, you could use a foreach loop to iterate through the result of a simpler XPath expression (once which only selects all of the TD elements) and find the highest number.
<?php
...
$xpath = new DOMXPath($doc);
$result = $xpath->evaluate('//table/tr/td');
$highest = '';
foreach ( $result as $node )
if ( $node->textContent > $highest )
$highest = $node->textContent;
echo $highest;
?>
You could also use the XSLTProcessor class and a XSL document that uses the math:max function from exslt.org but I've tried that and couldn't get it to work quite right because of the dollar signs ($).
I've tested both solutions and they worked well for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With