Pages

Search This Blog

Friday 12 October 2012

Find weather in PHP


<?php
/*
*Author : Zuh@ir
*Find weather using Yahoo weather API By Zipcode
*/
if(isset($_REQUEST['zipcode'])) {
if(isset($_POST['zipcode']) && is_numeric($_POST['zipcode'])){
    $zipcode = $_POST['zipcode'];
}else{
    $zipcode = '50644';
}
$result = file_get_contents('http://weather.yahooapis.com/forecastrss?p=' . $zipcode . '&u=f');
$xml = simplexml_load_string($result);

//echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');

$xml->registerXPathNamespace('yweather', 'http://xml.weather.yahoo.com/ns/rss/1.0');
$location = $xml->channel->xpath('yweather:location');

if(!empty($location)){
    foreach($xml->channel->item as $item){
        $current = $item->xpath('yweather:condition');
        $forecast = $item->xpath('yweather:forecast');
        $lat = $item->xpath('geo:lat');
        $lng = $item->xpath('geo:long');
        $current = $current[0];
        $output = <<<END
            <h2 style="margin-bottom: 0">Weather for {$location[0]['city']}, {$location[0]['region']}</h2>
            <div>{$current['date']}</div>
            <h2>Current Conditions</h2>
            <p>
            <span style="font-size:42px; font-weight:bold;">{$current['temp']}&deg;F</span>
            <br/>
            <img src="http://l.yimg.com/a/i/us/we/52/{$current['code']}.gif" style="vertical-align: middle;"/>&nbsp;
            {$current['text']}
            </p>
            <h2>Forecast</h2>
            {$forecast[0]['day']} : {$forecast[0]['text']}.  High: {$forecast[0]['high']}&#176;F,  Low: {$forecast[0]['low']}&#176;F
            <br/>
            {$forecast[1]['day']} : {$forecast[1]['text']}.  High: {$forecast[1]['high']}&#176;F,  Low: {$forecast[1]['low']}&#176;F
            </p>
END;
    }
}else{
    $output = '<h1>No results found, please try a different zip code.</h1>';
}
}else{
 
    $output = '';
}
?>
<script>
    function validateZipcode(){ //alert("test");
        if (!/^\d{5}$|^\d{5}-\d{4}$/.test(form.zipcode.value)) {
            alert("Please enter valid Zip Code");
            form.zipcode.focus()
            return false;}
    }
</script>

<form id="form" method="POST" action="">
<label>Please Enter Your Zipcode:</label> <input type="text" name="zipcode" size="8" value="" /><input onClick="return validateZipcode();" type="submit" name="submit" value="Lookup Weather" />

</form>
<hr />
<?php echo $output; ?>

2 comments:

  1. is this code does not show weather other than us

    ReplyDelete
  2. No, It shows weather no matter whatever the country is.

    ReplyDelete