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:

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

    $extn = 'log';

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

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

Here is the XML file:

<?xml version="1.0"?>
<group class="doc">
    <group icon="./.images/doc.png">
        <type extension="doc" description="Legacy Word Document" />
        <type extension="wps" description="Works Document" />

<group class="video">
    <group icon="./.images/video.png">
        <type extension="asf" description="Advanced Streaming Format" />
        <type extension="mpeg" description="Motion Picture Experts Video" />

I'd make heavier use of xpath:

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

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

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

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


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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy