weather api


12-09-2012 , well, after a study, a  CORS (cross origin resource sharing) is not allowed in IE 9, so  we can never use javascript to do this, google weather is depracated. use yahoo weather api instead.

 before, we can use a google api like this:

		foreach ($this->codep as $value) {
			if ($value==null || $value=="")
				continue;
			$fp = @fopen("http://www.google.com/ig/api?weather=". $value.",france", "r");
			break;
		}

		
		if (!$fp){
			return false;
		}
		$gt = "";
		while (!feof($fp) ) {
			$gt .= fgets($fp, 4096);
		}

		$p1 = strpos($gt, "");
		$p2 = strpos($gt, "");
		$gt2 = substr($gt, $p1, ($p2 - $p1));

		preg_match("/humidity data=\"Humidity: ([^\"]*)%\"/", $gt2, $humidite);
		preg_match("/wind_condition data=\"Wind: ([^\"]*) at ([^\"]*) mph\"/",
				$gt2, $vent);
		preg_match("/icon data=\"([^\"]*)\"/", $gt2, $lien);
		preg_match("/temp_c data=\"([^\"]*)\"/", $gt2, $temperature);
in $lien we got the weather icon.
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');
        $current = $current[0];
        $output = <<Weather for {$location[0]['city']}, {$location[0]['region']}
{$current['date']}
            

Current Conditions

{$current['temp']}°F
  {$current['text']}

Forecast

{$forecast[0]['day']} - {$forecast[0]['text']}. High: {$forecast[0]['high']} Low: {$forecast[0]['low']}
{$forecast[1]['day']} - {$forecast[1]['text']}. High: {$forecast[1]['high']} Low: {$forecast[1]['low']} END; } }else{ $output = '

No results found, please try a different zip code.

'; }

评论

热门博文