0

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.

Chuck
  • 3
  • 1
  • You're not using xpath. That would be something like $xml->xpath(`$path)`; – VolkerK Jun 04 '10 at 12:39
  • possible duplicate of [XML with xpath and PHP: How to access the text value of an attribute of an entry](http://stackoverflow.com/questions/1912240/xml-with-xpath-and-php-how-to-access-the-text-value-of-an-attribute-of-an-entry) ***EDIT: this one: [XML with xpath and PHP: How to access the text value of an attribute of an entry](http://stackoverflow.com/questions/992450/simplexml-selecting-elements-which-have-a-certain-attribute-value)*** – hakre Jul 01 '13 at 12:56

2 Answers2

1

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";
}
salathe
  • 51,324
  • 12
  • 104
  • 132
0

Use:

//UNIT[@index=$value]/ID

Community
  • 1
  • 1
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431