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);
$xml->registerXPathNamespace(
'yweather',
'http://xml.weather.yahoo.com/ns/rss/1.0'
);
$astronomy = $xml->xpath('//yweather:astronomy');
$attributes = $astronomy[0]->attributes();
$sunrise = (string) $attributes['sunrise'];
$sunset = (string) $attributes['sunset'];
printf('In Bucharest, the sun rises at %s and sets at %s',
$sunrise, $sunset);
Needless to say, it worked. Enjoy Mooooody.
Some asshole flying a plane in front of my house at 7 in the morning just woke me up, interrupting my well deserved rest after Yahoo’s 24 hours hackathon. But this post is not about Cessnas spraying chemicals, it’s about one of the best programer oriented events I ever attended. Thank you Yahoo! for making it possible.
Starting yesterday, my Pidgin stopped connecting to Yahoo!’s messenger service (MSN kept working). Being lazy, I’ve just changed the scs.msg.yahoo.com host to 66.163.181.166 in the user profile panel – the first solution I’ve came across on Google – and it started working again. For another day or so.