Friday, September 16, 2011

Iterate Over Nested / Multi-Level DOM NodeList

<?php
function processNodeList($nodeList)
{
    # text nodes don't have child nodes
    if ($root->nodeName == '#text')
    {
        $xml = $root->nodeValue;
    }
    else
    {
        # start tag
        $xml = sprintf('<%s>', $root->nodeName);
        # contents
        foreach ($root->childNodes as $node)
        {
            $xml .= processNodeList($node);
        }
        #end tag
        $xml .= sprintf('', $root->nodeName);
        # for some reason the blog puts html comment tags around the closing sprintf, just FYI to remove those as they are not intended
    }
    return $xml;
}

$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);

$nodeList = $xpath->query('/');
$xml = processNodeList($nodeList);

echo $xml; 
?>