Skip to content

Obtaining min/max values of an element with xpath

I have an xml sheet like:

    <f:device name="Voltage Converter" quantity="2" serial_number="20011">
        <f:weight units="pounds">3.00</f:weight>
    <f:device name="24-port switch" quantity="2" serial_number="24PORTSW-004">
        <f:weight units="pounds">3.34</f:weight>

I am obtaining the weight of the devices using simplexml and xpath like so:

foreach($xml->xpath('//f:weight[@units="pounds"]') as $weightLB) {
        echo $weightLB;
        echo "</br>";

I am trying to figure out how I can obtain the min and max values of the weight element. I have looked at many solutions regarding xpath but most cover attribute values and are not applicable to a sheet formatted like this. Any help would be appreciated!



You can map all the values to an array then use max and min functions:


$xml = <<<XML
<?xml version='1.0'?>
    <device name="Voltage Converter" quantity="2" serial_number="20011">
        <weight units="pounds">3.00</weight>
    <device name="24-port switch" quantity="2" serial_number="24PORTSW-004">
        <weight units="pounds">3.34</weight>

$simpleXml = simplexml_load_string($xml);

$weights = array_map(function($elem) {
    return $elem->__toString();
}, $simpleXml->xpath('//weight[@units="pounds"]'));

echo "Min: " .min($weights) . "<br/>";
echo "Max: " .max($weights);


Min: 3.00

Max: 3.34

User contributions licensed under: CC BY-SA
10 People found this is helpful