A Quick Weather API with PHP
I wanted to add a small weather status to the top of a web application, just to remind me what was going on in that city. This is some really simple code, based off of WunderGround’s API, using a city airport’s conditions. Not going into much detail on this, or offering a completely robust solution, but here is the code I have in place.

$url = 'http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=KSFO'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $data = curl_exec($ch); curl_close($ch); $xml = simplexml_load_string($data); $weather = $xml->weather; $temp = $xml->temp_f; $icon = $xml->icons->icon_set[9]->icon_url;
From this, you can set the three parsed variables into your html, and you are all set.
<img src="<?= $icon ?>"/> <h3 style="margin-bottom:30px;">It's currently <?= $temp ?>° and <?= $weather ?> in California.</h3>
I am finding the call to take about 0.20s, which is acceptable to keep it all in PHP right now. Hope this helps in your quest.
Comments