While developing mooooody.com at Yahoo’s hackathon, I stumbled on a small problem: parsing Yahoo Weather’s results in PHP with simple_xml. The problem arose from Yahoo’s use of the yweather: namespace. By default, SimpleXML cannot parse tags like yweather:astronomy.
Being somewhat intellectually impaired by prolonged sleep depravation – I thought to just search the web for a solution and not come up with one myself. It was a hackathon, the point was to hack the app together fast, not write state of the art code. So, after a bit of googling around, I landed on this spanish blog. The guy’s idea was to just do a str_replace to remove all the yweather: bits and then parse it as regular XML. After a short talk with the team, we decided that we’re not *that* tired and we looked for a better solution.
Which came shortly after in the form of registering the proper namespace with the SimpleXML object. Check it out:
$response = file_get_contents('http://weather.yahooapis.com/forecastrss?w=868274&u=c');
$xml = new SimpleXMLElement($response);
$astronomy = $xml->xpath('//yweather:astronomy');
$attributes = $astronomy->attributes();
$sunrise = (string) $attributes['sunrise'];
$sunset = (string) $attributes['sunset'];
printf('In Bucharest, the sun rises at %s and sets at %s',
Needless to say, it worked. Enjoy Mooooody.