Better SimpleXML parsing method I am trying to parse this XML file. I have the extension and I need to get the description, icon, and class from the XML. My code works(ish) (I know how to continue from where I am), but it doesn't seem very elegant. Is there a better way of doing this?

Here is the PHP code:

&lt;?php
if($xml = simplexml_load_file('formats.xml')) {
    echo 'the file was loaded successfully';

    $extn = 'log';

    $xmltypes = $xml-&gt;xpath('//type');

    foreach($xmltypes as $node) {
        foreach($node-&gt;attributes() as $name =&gt; $attrib) {
            if($name=='extension') {
                if($attrib==$extn) {
                    $parent = $node-&gt;xpath('..');
                    foreach($parent[0]-&gt;attributes() as $a =&gt; $b) {
                        if($a=='class')
                            $class = $b;
                        if($a=='icon')
                            $icon = $b;
                    }
                }
            }
        }
    }
    echo $extn.'&lt;br&gt;';
    echo $icon.'&lt;br&gt;';
    echo $class.'&lt;br&gt;';
}
else {
    echo 'the file was not loaded';
}
?&gt;


Here is the XML file:

&lt;?xml version="1.0"?&gt;
&lt;extensions&gt;
&lt;group class="doc"&gt;
    &lt;group icon="./.images/doc.png"&gt;
        &lt;type extension="doc" description="Legacy Word Document" /&gt;
        ...
        ...
        &lt;type extension="wps" description="Works Document" /&gt;
    &lt;/group&gt;
&lt;/group&gt;

&lt;group class="video"&gt;
    &lt;group icon="./.images/video.png"&gt;
        &lt;type extension="asf" description="Advanced Streaming Format" /&gt;
        ...
        ...
        &lt;type extension="mpeg" description="Motion Picture Experts Video" /&gt;
    &lt;/group&gt;
&lt;/group&gt;
&lt;/extensions&gt;
I'd make heavier use of xpath:

$xml = simplexml_load_string($x); // assume XML in $x
$class = $xml-&gt;xpath("//type[@extension = 'doc']/../../@class")[0];
$icon = $xml-&gt;xpath("//type[@extension = 'doc']/../@icon")[0];
$description = $xml-&gt;xpath("//type[@extension = 'doc']/@description")[0];

echo "$class | $icon | $description";


My code requires PHP >= 5.4, for older versions, do:

$class = $xml-&gt;xpath("//type[@extension = 'doc']/../../@class");
$class = $class[0];


or...

list($class,) = $xml-&gt;xpath("//type[@extension = 'doc']/../../@class");