Raphael Portmann
Raphael Portmann

Reputation: 33

PHP - Get value of an XML element attribute by searching another attribute identifier

I'm trying to get some informations out of a xml string with php.

Heres the example:

<test>
 <item id="29489" name="Strawberry" str="nd93n1jn"/>
 <item id="24524" name="Apple" str="df89ah3n"/>
 <item id="84452" name="Banana" str="27g3vhvr"/>
 <item id="01834" name="Kiwi" str="h32h8329"/>
 <item id="27483" name="Coconut" str="98hf3ubf"/>
 <item id="34892" name="IDK" str="2hbf34wk"/>
</test>

How can I get for example the 'name' string when I know the 'id' string?

Upvotes: 2

Views: 139

Answers (1)

Gabe
Gabe

Reputation: 1183

One way to do this is by parsing the XML into an array structure. Then just looking at the array values with a simple for loop:

$simple = '<test>
 <item id="29489" name="Strawberry" str="nd93n1jn"/>
 <item id="24524" name="Apple" str="df89ah3n"/>
 <item id="84452" name="Banana" str="27g3vhvr"/>
 <item id="01834" name="Kiwi" str="h32h8329"/>
 <item id="27483" name="Coconut" str="98hf3ubf"/>
 <item id="34892" name="IDK" str="2hbf34wk"/>
</test>';

 $p = xml_parser_create();
xml_parse_into_struct($p, $simple, $outArray, $index);
xml_parser_free($p);

$needle="84452";

for($i=0;$i<count($outArray);$i++){ 
    if (array_key_exists('attributes', $outArray[$i])) {
            if($outArray[$i]['attributes']['ID']==$needle){ 
                echo "found it, its name is: " . $outArray[$i]['attributes']['NAME'];
            } 
    } 
}

Note that the XML's attributes are stored in a sub-array called the same way(attributes) when you use the xml_parse_into_struct function. Also notice that the array keys when created using xml_parse_into_struct are converted to UPPERCASE by default(look i used uppercase in the search). If case is important, you need to add this option just prior to invoking xml_parse_into_struct:

xml_parser_set_option($p,XML_OPTION_CASE_FOLDING,0);

Upvotes: 2

Related Questions