home   articles   tags   browse code   

XML Parsing with PHP DOMDocument


 

PHP5 has several XML parsers built in, here is some sample code for parsing with DOM XML. It is by no means an exhaustive example, but it is some code to get your feet wet. This example uses the XML RSS feed for this site.

<?php
$file  = file_get_contents("http://feeds.feedburner.com/Zedwood-Code-Articles");
$doc   = DOMDocument::loadXML($file);

for($i=0; $i<$doc->childNodes->length; $i++)
{
    $tag = $doc->childNodes->item($i);
    if ($tag->nodeName=="rss")
    {
        $rss = $tag;
        echo "<br>** ".$tag->nodeName;
        for($j=0; $j<$rss->childNodes->length; $j++)
        {
            $tag = $rss->childNodes->item($j);
            if ($tag->nodeName=="channel")
            {
                $chan = $tag;
                echo "<br>*** ".$tag->nodeName;
                for($k=0; $k<$chan->childNodes->length; $k++)
                {
                    $tag = $chan->childNodes->item($k);
                    if      ($tag->nodeName=="title")        { echo "<br>****",$tag->nodeName; }
                    else if ($tag->nodeName=="link" )        { echo "<br>****",$tag->nodeName; }
                    else if ($tag->nodeName=="description" ) { echo "<br>****",$tag->nodeName; }
                    else if ($tag->nodeName=="item" )
                    {
                        $item = $tag;
                        echo "<br>**** ".$tag->nodeName;
                        for($l=0; $l<$item->childNodes->length; $l++)
                        {
                            $tag = $item->childNodes->item($l);
                            if ($tag->nodeName=='title')
                                echo "<br>*****".$tag->nodeName." ".$tag->nodeValue;
                            else if ($tag->nodeName=='link')
                                echo "<br>*****".$tag->nodeName." ".$tag->nodeValue;
                            else
                                echo "<br>*****".$tag->nodeName." len(".strlen($tag->nodeValue).")";
                        }
                    }
                }
            }
        }
    }
}
?>

 

Tags: xml, php
 


 

 



Related Articles
 



home  |  privacy policy  |  terms of use  |  contact  


©2010, Zedwood Digital