Parsing XML with PHP

Parsing XML using PHP is pretty easy. PHP has an extension called SimpleXML that “provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.” Check out the example below to see how it works. The PHP code is first with the sample XML below it.

<?php
    $xml = simplexml_load_file("http://news.ycombinator.com/rss");

    $items = $xml->channel->item;

    for($i = 0; $i < count($items); $i++) { 
        $title = $items[$i]->title;
        $url = $items[$i]->link;
        echo "<a href='" . $url . "'>" . $title . "</a>";
    }
?>

<rss version="2.0">
    <channel>
        <title>Hacker News</title>
        <link>http://news.ycombinator.com/</link>
        <description>Links for the intellectually curious, ranked by readers.</description>
        <item>
            <title>Sphinxtr: Creating a Portable PhD Thesis</title>
            <link>http://jterrace.github.com/sphinxtr/singlehtml/index.html</link>
            <comments>http://news.ycombinator.com/item?id=4609769</comments>
            <description>
                <![CDATA[<a href="http://news.ycombinator.com/item?id=4609769">Comments</a>]]>
            </description>
            </item>
    </channel>
</rss>