WordPressに天気予報表示を付けてみる3

WordPressに天気予報表示を付けてみる2では、livedoorのWeather Hacksを使った天気予報表示を試してみたが、次はGoogle Weather APIを利用した天気予報表示を試してみる。
cssは省略。

<?php

// APIからXMLデータ取得
$city = 'osaka,osaka';
$gpath = 'http://www.google.com';
$url = $gpath . '/ig/api?weather=';
// 取得データから表示項目取得

$xml = simplexml_load_file($url . $city);

$objInfo =  $xml->weather->forecast_information;
$first_date = $objInfo->forecast_date[data];

echo '<div>in ' . strtoupper($objInfo->postal_code[data]) . '<br>';

$i = 0;
foreach ($xml->weather->forecast_conditions as $cond) {
	$week = $cond->day_of_week[data];
	$icon_url = $gpath . $cond->icon[data];
	$low = $cond->low[data];
	$high = $cond->high[data];
	$condition = str_replace('Chance of ', '', $cond->condition[data]);
	
	echo '<div>';
	echo '<img src="' . $icon_url . '" alt="icon" />';
	echo '<div>' . '';
	echo date('Y-m-d', strtotime ($first_date) + $i * 86400) .'[' . $week . ']<br>' . $condition . ' ';
	if (strlen($low) > 0 || strlen($high) > 0) {
		echo strlen($low)>0 ? convertF2C($low) : '';
		echo '-' ;
		echo strlen($high)>0 ? convertF2C($high) : '';
		echo '℃' ;
	}
	echo '</div>';
	echo '</div>';
	$i++;
}
echo '</div>';

//華氏摂氏変換
function convertF2C($val) {
	return round(($val-32)*5/9);
}
?>

Google Weather APIでは今日を含めた4日分の予報が取得できる。

Add a Comment

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください