PHP by example - Simple XML Parsing with SimpleXML


I have read and answered some PHP questions related to XML at DevNetwork Forums, many PHP programmer does not know how to parse XML into string from external resources. Let take an example, I would like to have a Kuala Lumpur weather forecast for my blog, I can retrieve the information from Yahoo! Weather RSS feed in XML formatted document, how do I parse the XML into string using PHP? You just have to use php_get_contents function with SimpleXML extension :

<?php
 
// get kuala lumpur wheather forecast 
$content = file_get_contents('http://xml.weather.yahoo.com/forecastrss?p=MYXX0008');
 
// parse the xml document to array
$xml = new SimpleXMLElement($content);
 
// print the xml element into string
print_r($xml);
 
?>

There is a better way to process the RSS feeds, Read my previous post about Zend_Feed.

Post a Comment

*Required
*Required (Never published)