Skip to content
Advertisement

Obtaining min/max values of an element with xpath

I have an xml sheet like:

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

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!

Advertisement

Answer

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

<?php

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

$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);

Output:

Min: 3.00

Max: 3.34

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