0
\$\begingroup\$

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:

<?php
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) {
                        if($a=='class')
                            $class = $b;
                        if($a=='icon')
                            $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"?>
<extensions>
<group class="doc">
    <group icon="./.images/doc.png">
        <type extension="doc" description="Legacy Word Document" />
        ...
        ...
        <type extension="wps" description="Works Document" />
    </group>
</group>

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

migrated from stackoverflow.com Aug 31 '13 at 21:32

This question came from our site for professional and enthusiast programmers.

2
\$\begingroup\$

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];

or...

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

Your Answer

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