Saturday, 17 January 2015

Recursive XML path parsing

I was asked yesterday for some help with PHP at work... this was something of a shock! Not only was it a shock because someone was asking me for help with something other than javascript, but they wanted help with PHP!

Anyway - the requirement was to list all possible routes through an XML file and at the time I suggested an iteration over each branch elements of a given trunk... but I did say that it would be better to use a recursive function. Then the pattern of the recursive function came to me about 05:00 this morning so I wrote a simple example to get all possible routes through an XML file:

<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
    <movie>
        <title>PHP: Behind the Parser</title>
        <characters>
            <character>
                <name>Ms. Coder</name>
                <actor>Onlivia Actora</actor>
            </character>
            <character>
                <name>Mr. Coder</name>
                <actor>El Act&#211;r</actor>
            </character>
        </characters>
        <plot>
            So, this language. It's like, a programming language. 
            Or is it a scripting language? All is revealed in this 
            thrilling horror spoof of a documentary. 
        </plot>
        <great-lines>
            <line>PHP solves all my web problems</line>
        </great-lines>
        <rating type="thumbs">7</rating>
        <rating type="stars">5</rating>
    </movie>
</movies>
XML;

$movies = new SimpleXMLElement($xmlstr);

getPaths($movies->getName(), $movies);

function getPaths($str, $xml){
    $children = $xml->children();
    if($children->count() > 0){
        foreach($children as $child){
            getPaths($str."/".$child->getName(), $child);
        }
    }else{
        echo $str."<br/>";
    }
}

I do like recursion but it does sometimes need me to think about it a wee bit before clocking what it is I need to do and how to do it.