PHP parse xml with SimpleXML 

Joined:
03/10/2011
Posts:
84

April 05, 2011 09:32:34    Last update: April 05, 2011 09:33:49
It's easy to parse xml in PHP using SimpleXML.
<?php
$xml_string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>

<rss version="2.0">
    <channel>
	<title>NASA Breaking News</title>
	<link>http://www.nasa.gov/audience/formedia/features/index.html</link>
	<description>
	    A RSS news feed containing the latest NASA news articles and press releases.
	</description>
	<language>en-us</language>
	<docs>http://blogs.harvard.edu/tech/rss</docs>
	<managingEditor>jim.wilson@nasa.gov</managingEditor>
	<webMaster>brian.dunbar@nasa.gov</webMaster>
	
	<item>
	    <title>Brian Basset Creates Commemorative Space Shuttle Cartoon</title> 
	    <link>http://www.nasa.gov/home/hqnews/2011/apr/HQ_11-100_Shuttle_Poster.html</link> 
	    <guid>http://www.nasa.gov/home/hqnews/2011/apr/HQ_11-100_Shuttle_Poster.html</guid> 
	    <description>
		Comic strip artist Brian Basset has created a drawing depicting his characters, 
		Red and Rover, racing alongside the space shuttle as it lands for the final time.
	    </description> 
	    <pubDate>Tue, 05 Apr 2011 00:00:00 EDT</pubDate> 
	</item> 
	
	<item>
	    <title>NASA Extends Contract For Supercomputing Support Services</title> 
	    <link>http://www.nasa.gov/home/hqnews/2011/mar/HQ_C11-015_Supercomputing.html</link> 
	    <guid>http://www.nasa.gov/home/hqnews/2011/mar/HQ_C11-015_Supercomputing.html</guid> 
	    <description>
		NASA will exercise the third one-year option on a contract with Computer Sciences 
		Corp. in Lanham, Md., to provide supercomputing support services at NASA's Ames 
		Research Center at Moffett Field, Calif.
	    </description> 
	    <pubDate>Fri, 01 Apr 2011 00:00:00 EDT</pubDate> 
	</item> 
    </channel>
</rss>
XML;

# Load xml from string
$xml = simplexml_load_string($xml_string);
echo '<h1>Cached news</h1>', "\n";
foreach ($xml->channel->item as $item)
{
   echo $item->title, "<br/>\n";
}

# Load xml from file
$xml = simplexml_load_file("http://www.nasa.gov/rss/breaking_news.rss");
echo "\n", '<h1>Live news</h1>', "\n";
foreach ($xml->channel->item as $item)
{
   echo $item->title, "<br/>\n";
}
?>


Dealing with errors:
<?php
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if (!$sxe) {
    echo "Failed loading XML\n";
    foreach(libxml_get_errors() as $error) {
        echo "\t", $error->message;
    }
}
?>

Share |
| Comment  | Tags