weather mapのデータをDBに格納する

テーブル名はcakeを使うので、複数形にします。

create table weather.marunouchis(
	id int unsigned auto_increment primary key,
	forecast varchar(255),
	main varchar(255),
	description varchar(255),
	temp float,
	humidity int,
	cloud int,
	speed float,
	created datetime default null
);

PDO::PARAM_INTは、floatやdoubleはないとのこと。指定しないとstrになる。

$now = date("Y-m-d H:i:s");
$i = 0;
foreach($main as $value){
    $stmt->bindParam(':forecast', $time[$i], PDO::PARAM_STR);
    $stmt->bindParam(':main', $value, PDO::PARAM_STR);
    $stmt->bindParam(':description', $description[$i], PDO::PARAM_STR);
    $stmt->bindParam(':temp', $temp[$i], PDO::PARAM_STR);
    $stmt->bindParam(':humidity', $humidity[$i], PDO::PARAM_INT);
    $stmt->bindParam(':cloud', $cloud[$i], PDO::PARAM_INT);
    $stmt->bindParam(':speed', $speed[$i], PDO::PARAM_INT);
    $stmt->bindParam(':created', $now, PDO::PARAM_STR);
    $stmt->execute();
    $i++;
}

入っていますね。

取得した時刻が現在より未来か過去か判定する

strtotimeを使ってUNIXタイムスタンプに変換して比較します。

$now = date("Y-m-d H:i:s");
if(strtotime($now) > strtotime($list[10]["dt_txt"])){
	echo "過去の天気です。";
}else if(strtotime($now) <= strtotime($list[10]["dt_txt"])){
    echo "未来の天気です。";  
} else{
	echo "比較に失敗しました。";
}

今より、未来の天気予報を表示する

$now = date("Y-m-d H:i:s");

echo "<table class=\"table1\">";
echo "<tr>";

$i = 1;
foreach($list as $value){
	if(strtotime($now) <= strtotime($value&#91;"dt_txt"&#93;)){
	echo "<td>";
    $date = $value["dt_txt"];
    echo date('n月j日 H時', strtotime($date)). "<br>";
	echo convert($value["weather"][0]["main"]) . "<br>";
	echo "<span style=\"color:gray;\">".convert2($value["weather"][0]["description"]) . "</span><br>";
	$temp = $value["main"]["temp"];
	echo "気温 : " . number_format(($temp - 273.15),1) . "°<br>";
	echo "湿度 : " . $value["main"]["humidity"] . "%<br>";
	echo "雲 : " . $value["clouds"]["all"] . "%<br>";
	echo "風速 : " . $value["wind"]["speed"] . "m<br><br>";
	echo "</td>";
	if($i % 8 == 0){
	echo "</tr><tr>";
	}
	$i++;
	}
	

}
echo "</tr>";
echo "</table>";

なるほど、なかなかいいんじゃないでしょうか?

Yahoo天気
23区全部ありますね。。チ。

天気の英語から日本語への変換

一つづつstr_replaceで変換を考えましたが、

str_replace("Clear","晴れ", $main);

ここではswitch文を使ってみます。

foreach($list as $value){
	$main = $value["weather"][0]["main"];
		switch($main){
			case 'Clear':
				echo "晴れ<img src=\"icon01.png\"><br>";
				break;
			case 'Clouds':
				echo "曇<img src=\"icon02.png\"><br>";
				break;
			case 'Rain':
				echo "雨<img src=\"icon03.png\"><br>";
				break;
			default:
				echo $main;
		}
}

functionにします。

function convert($main){
	switch($main){
			case 'Clear':
				return "晴れ<img src=\"icon01.png\">";
				break;
			case 'Clouds':
				return "曇<img src=\"icon02.png\">";
				break;
			case 'Rain':
				return "雨<img src=\"icon03.png\">";
				break;
			default:
				echo $main;
		}
}

悪くないです。良くもないが。。

descriptionも関数を作ってみます。

function convert2($description){
	switch($description){
			case 'clear sky':
				return "晴天<br>";
				break;
			case 'scattered clouds':
				return "きれぎれに浮かんでいる雲";
				break;
			case 'broken clouds':
				return "ちぎれた雲<br>";
				break;
			case 'few clouds':
				return "少しの雲<br>";
				break;
			case 'light rain':
				return "小雨<br>";
				break;
			default:
				echo $description;
		}
}

日付形式の変換

2018-03-10 09:00:00
3月10日 09時

Y/m/d H:i:s
Y/n/j H:i:s

mはゼロ詰め、nはゼロつめなし。
dはゼロ詰め、jはゼロつめなし。

echo date('n月j日 h時', strtotime($date));

あれ、15時が03時になってますね。駄目ですね。

H大文字だと、15時、18時、21時と表示されました。

date('n月j日 H時', strtotime($date))

天気予報を表示してみよう

tdを8(=24/3)にして、テーブルで表示してみます。

<style>
.table1 td {
	width: 120px;
	height: 260px;
	vertical-align: top;
}

</style>
<?php

$city = "Marunouchi";
$API_KEY = "foo";
$BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/?q=".$city.",jp&appid=" . $API_KEY . "";

$forecast = json_decode(file_get_contents($BASE_URL), true);

echo "<b>" . $city . "</b><br>";
$list = $forecast["list"];

echo "<table class=\"table1\">";
echo "<tr>";

$i = 1;
foreach($list as $value){
	echo "<td>";
	echo $value["dt_txt"] . "<br>";
	echo $value["weather"][0]["main"] . "<br>";
	echo $value["weather"][0]["description"] . "<br>";
	$temp = $value["main"]["temp"];
	echo "気温 : " . ($temp - 273.15) . "°<br>";
	echo "湿度 : " . $value["main"]["humidity"] . "%<br>";
	echo "雲 : " . $value["clouds"]["all"] . "%<br>";
	echo "風速 : " . $value["wind"]["speed"] . "m<br><br>";
	echo "</td>";
	if($i % 8 == 0){
	echo "</tr><tr>";
	}
	$i++;

}
echo "</tr>";
echo "</table>";
?>

やべー

PHPで丸の内の天気を取得してみよう

<?php

$city = "Marunouchi";
$API_KEY = "not watch";
$BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/?q=".$city.",jp&appid=" . $API_KEY . "";

$forecast = json_decode(file_get_contents($BASE_URL), true);

echo $city . "<br>";
$list = $forecast["list"];
echo $list[0]["dt_txt"] . "<br>";
echo $list[0]["weather"][0]["main"] . "<br>";
echo $list[0]["weather"][0]["description"] . "<br>";
$temp = $list[0]["main"]["temp"];
echo "気温 : " . ($temp - 273.15) . "°<br>";
echo "湿度 : " . $list[0]["main"]["humidity"] . "%<br>";
echo "雲 : " . $list[0]["clouds"]["all"] . "%<br>";
echo "風速 : " . $list[0]["wind"]["speed"] . "m<br>";
?>

foreachに書き換えます。

echo "<b>" . $city . "</b><br>";
$list = $forecast["list"];

foreach($list as $value){
	echo $value["dt_txt"] . "<br>";
	echo $value["weather"][0]["main"] . "<br>";
	echo $value["weather"][0]["description"] . "<br>";
	$temp = $value["main"]["temp"];
	echo "気温 : " . ($temp - 273.15) . "°<br>";
	echo "湿度 : " . $value["main"]["humidity"] . "%<br>";
	echo "雲 : " . $value["clouds"]["all"] . "%<br>";
	echo "風速 : " . $value["wind"]["speed"] . "m<br><br>";
}

うわーでたー

open weather map api  listの中身

listの中身を見てみましょう。取得日を含めて5日分のデータが返ってきます。
一番下の”dt_txt”がその日時のようですね。3時間おきにあります。
09:00:00
12:00:00
15:00:00
18:00:00
21:00:00
00:00:00
03:00:00
06:00:00

[“temp”]=>float(278.11) はケルビンで、273.15を引くと℃になります。
[“pressure”]=>float(994.69) は気圧。hpa
[“deg”]=>float(55.0004) は風向き

気圧はahp

[1]=>
    array(9) {
      ["dt"]=>
      int(1520683200)
      ["main"]=>
      array(8) {
        ["temp"]=>
        float(278.11)
        ["temp_min"]=>
        float(277.249)
        ["temp_max"]=>
        float(278.11)
        ["pressure"]=>
        float(994.69)
        ["sea_level"]=>
        float(1035.79)
        ["grnd_level"]=>
        float(994.69)
        ["humidity"]=>
        int(100)
        ["temp_kf"]=>
        float(0.86)
      }
      ["weather"]=>
      array(1) {
        [0]=>
        array(4) {
          ["id"]=>
          int(500)
          ["main"]=>
          string(4) "Rain"
          ["description"]=>
          string(10) "light rain"
          ["icon"]=>
          string(3) "10n"
        }
      }
      ["clouds"]=>
      array(1) {
        ["all"]=>
        int(80)
      }
      ["wind"]=>
      array(2) {
        ["speed"]=>
        float(1.18)
        ["deg"]=>
        float(55.0004)
      }
      ["rain"]=>
      array(1) {
        ["3h"]=>
        float(0.31)
      }
      ["snow"]=>
      array(0) {
      }
      ["sys"]=>
      array(1) {
        ["pod"]=>
        string(1) "n"
      }
      ["dt_txt"]=>
      string(19) "2018-03-10 12:00:00"
    }

open weather map api

まず、city listをダウンロードします。
http://bulk.openweathermap.org/sample/

コマンドラインで、解凍します。
$ gzip -d city.list.json.gz

すると、city.list.jsonができます。

[vagrant@localhost weather]$ ls
city.list.json  index.php

jpanの国コードはjp
データを見てみましょう。

  {
    "id": 1850144,
    "name": "Tōkyō-to",
    "country": "JP",
    "coord": {
      "lon": 139.691711,
      "lat": 35.689499
    }
  },
  {
    "id": 1848354,
    "name": "Yokohama-shi",
    "country": "JP",
    "coord": {
      "lon": 139.642502,
      "lat": 35.447781
    }
  },

では、今回は丸の内(“Marunouchi”)でデータを取得してみます。
API Keyはサイトで30秒くらいで取得できます。
https://home.openweathermap.org/api_keys

<?php

$city_code = "Marunouchi";
$API_KEY = "hoge";
$BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/?q=Hachioji,jp&appid=".$API_KEY."";

$forecast = json_decode(file_get_contents($BASE_URL), true);

echo "<pre>";
var_dump($forecast);
echo "</pre>";
?>

weather rain など返ってきてますね。

mysqlでuniqueを後から追加

alter table music01 add unique (title);

入ってますね。

既にテーブルの中の値が重複している場合は、一度削除しなければなりません。

また、既にuniqueが設定されている場合は、上書きされて、uniqueが設定されます。
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0