Search code examples
phpxpathsimplexmlattributesparent

Access value through parent attribute


I am looking to get the value A-1 through xpath based on a passed attribue.

I have passed the index attribute of the unit through php from a previous page and am accessing it by global GET:

$value = intval($_GET['index']);

the xml:

<UNIT index='1'>
     <ID>A-1</ID>
     <MANUFACTURER>testing inc.</MANUFACTURER>
</UNIT>
<UNIT index='2'>
     <ID>A-2</ID>
     <MANUFACTURER>testing inc.</MANUFACTURER>
</UNIT>

I'm trying to echo it out using:

$xml = new SimpleXMLElement('demo.xml',NULL,true);

echo $xml->UNIT[$value]->ID;

I know i'm getting the "1" that I need passed through because I echo'd $value to check, but its giving me the ID of A-2, which would be the xml index number (starting from 0) - not my attribute index number.


Solution

  • You can use the SimpleXMLElement::xpath method to query for the specific UNIT that you want with an XPath query like //UNIT[@index=2].

    $value = intval($_GET['index']);
    $xml   = new SimpleXMLElement('demo.xml',NULL,true);
    $units = $xml->xpath("//UNIT[@index=$value]"); // xpath returns an array
    if (isset($units[0])) {
        echo $units[0]->ID;
    } else {
        echo "No unit with index $value";
    }