タグ: PHP

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日分の予報が取得できる。

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

「WordPressに天気予報表示を付けてみる」のphpコード

<?php
// APIからXMLデータ取得
$city = '81';
$url = 'http://weather.livedoor.com/forecast/webservice/rest/v1?city=';

// 取得データから表示項目取得
// 今日
$xml = simplexml_load_file($url . $city . '&amp;day=today');
echo '<div>';
outputWeatherInfomation($xml);

// 明日
$xml = simplexml_load_file($url . $city . '&amp;day=tomorrow');
outputWeatherInfomation($xml);

// 明後日(地区の出力)
$xml = simplexml_load_file($url . $city . '&amp;day=dayaftertomorrow');
outputWeatherInfomation($xml);
echo '<strong>in ' . $xml->location->attributes()->pref . $xml->location->attributes()->city . '市</strong><br>';
echo '</div>';

// 市区町村
echo '<br style="clear:both;">';
//outputPointInfomation($xml);

// 取得したXMLより天気情報出力
function outputWeatherInfomation($xml) {
	echo '<div>';
	echo '<div>' . date_format(new DateTime($xml->forecastdate),'m/j') . '<br>';
	echo '<small>' . $xml->day . '</small></div>';
	echo '<img src="' . $xml->image->url . '" width="' . $xml->image->width
       . '" height="' . $xml->image->height . '" alt="' . $xml->image->title . '" /><br>';
	echo '<div>';
	echo $xml->telop . '<br>';
	if (strlen($xml->temperature->min->celsiu)>0 || strlen($xml->temperature->max->celsius)>0) {
		echo $xml->temperature->min->celsius . '~' . $xml->temperature->max->celsius.'℃<br>';
	}
	echo '</div>';
	echo '</div>';
}

// 取得したXMLより市区町村情報出力
function outputPointInfomation($xml) {
	echo '<div>';
	foreach($xml->pinpoint->location as $pnt) {
		echo '<a href="' . $pnt->link . '" target="_blank">' . $pnt->title . '</a>|';
	}
	echo '</div>';
}
?>

css等は省略。