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

cakeで遊んでみよう データベースの設計

まずCakeで作っていくには、ある程度データベースの設計ができていないといけない。
ということで、適当にcake用にデータベースをつくっていきます。テーブル名は複数形にする必要があります。

create table radio.channel01s(
	id int unsigned auto_increment primary key,
	artist varchar(255),
	album varchar(255),
        title varchar(255),
        mp3 varchar(255),
	youtube varchar(255)
);

create table radio.cover01s(
	artist varchar(255),
	album varchar(255),
	asin varchar(255),
	url varchar(8190)
);

create table radio.rankings(
	id int unsigned auto_increment primary key,
	status varchar(255),
	artist varchar(255)
);

OKですね。

そしてcakeをディレクトリにインストールします。この瞬間なぜか緊張します。
php composer.phar create-project –prefer-dist cakephp/app radio

入ったようです。

こちらでサーバーを起動します。
bin/cake server -H 192.168.33.10 -p 8000

連続再生中の曲のタイトルを表示する

audioをplay, pauseするfunctionの中で、playしているli要素をboldにして、textContentで渡せばいいだけですね♪♪♪

<h2>Catcher In The Light<div style="display:inline;" id="title"></div></h2>
<p><audio src="/mp3/180307112410.mp3" preload="none" onclick="playthis(1);" controls="controls"></audio></p>

<ul>
<li id="list1"><a href="javascript:playthis(1)">Catcher In The Light</a></li>
<li id="list2"><a href="javascript:playthis(2)">About You</a></li>
<li id="list3"><a href="javascript:playthis(3)">GAME</a></li>
<li id="list4"><a href="javascript:playthis(4)">my name's WOMEN</a></li>
<li id="list5"><a href="javascript:playthis(5)">WONDERLAND</a></li>
</ul>

<script type="text/javascript">

var dir = "/foo/";
// var now = " ← now playing";

var media = document.getElementsByTagName("audio")[0];

var list = new Array(5);
list[1] = "hoge.mp3";
list[2] = "hogehoge.mp3";
list[3] = "hogehogehoge.mp3";
list[4] = "hogehogehogehoge.mp3";
list[5] = "hogehogehogehogehoge.mp3";

var length = list.length;

var COOKIE = new Array();
if (document.cookie) {
	var cookies = document.cookie.split("; ");
	for (var i = 0; i < cookies.length; i++) {
		var str = cookies&#91;i&#93;.split("=");
		COOKIE&#91;str&#91;0&#93;&#93; = unescape(str&#91;1&#93;);
	}
}

var volume = isNaN(COOKIE&#91;"volume"&#93;) ? 0.5 : COOKIE&#91;"volume"&#93;;
media.volume = volume;

media.onended = function(){ 
	playnext(this.src); 
};

window.onbeforeunload = function(){ setCookie("volume", media.volume); };
</script>

<script type="text/javascript">

function playthis(key){
	media.pause();
	media.src = dir + list[key];
	media.play();

	var hoge =list[key];

    
    var tag = document.getElementById("list"+key).innerHTML;
    var title  = tag.replace(/<("&#91;^"&#93;*"|'&#91;^'&#93;*'|&#91;^'">])*>/g,'');
	var song = document.getElementById("title");
	song.textContent = " : " + title;

	// for(var i=1;i<length;i++) document.getElementById("list"+i).innerHTML = document.getElementById("list"+i).innerHTML.replace(now,"");
    for(var i=1;i<length;i++) document.getElementById("list"+i).style.fontWeight = "normal";
    document.getElementById("list"+key).style.fontWeight = "bold";
	// document.getElementById("list"+key).innerHTML += now;

	
}


function playnext(objsrc) {
	var objsrc = decodeURI(objsrc);
	objsrc = objsrc.replace("http://"+location.host,"");
	for (var i=1;i<length;i++) {
		var listsrc = dir + list&#91;i&#93;;
		if(objsrc===listsrc){
			if(length==i+1){
				document.getElementById("list"+i).innerHTML = document.getElementById("list"+i).innerHTML.replace(now,"");
				// 先頭を再生
				// playthis(1);
			}else{
				playthis(i+1);
			}
			break;
		}
	}
}

function setCookie(name, value, domain, path, expires, secure) {
	if (!name) return;
	domain = location.hostname;
	path = "/";
	expires = 30;

	var str = name + "=" + escape(value);
	if (domain) {
		if (domain == 1) domain = location.host.replace(/^&#91;^\.&#93;*/, "");
		str += "; domain=" + domain;
	}
	if (path) {
		if (path == 1) path = location.pathname;
		str += "; path=" + path;
	}
	if (expires) {
		var nowtime = new Date().getTime();
		expires = new Date(nowtime + (60 * 60 * 24 * 1000 * expires));
		expires = expires.toGMTString();
		str += "; expires=" + expires;
	}
	if (secure && location.protocol == "https:") {
		str += "; secure";
	}

	document.cookie = str;
}
</script>

ボタンを押すごとに、boldが変わる

fontWeightを判定します。

<p id="list1">Catcher In The Light</p>
<p id="list2">About You</p>
<p id="list3">GAME</p>
<input type="button" value="ボタン" onclick="changeFontWeight();">

<script>
function changeFontWeight(){
	var obj1 = document.getElementById("list1");
	var obj2 = document.getElementById("list2");
	var obj3 = document.getElementById("list3");
	if(obj1.style.fontWeight == "bold"){
		obj1.style.fontWeight = "normal";
		obj2.style.fontWeight = "bold";
	} else if(obj2.style.fontWeight == "bold") {
		obj2.style.fontWeight = "normal";
		obj3.style.fontWeight = "bold";
	} else if(obj3.style.fontWeight == "bold"){
		obj3.style.fontWeight = "normal";
		obj1.style.fontWeight = "bold";
	} else {
		obj1.style.fontWeight = "bold";
	}
}
</script>

変数をHTMLに渡して表示する

<h1>MyStory <div style="display:inline;" id="title"></div></h1>

<p id="list1">Catcher In The Light</p>
<p id="list2">About You</p>
<p id="list3">GAME</p>
<input type="button" value="ボタン" onclick="changeFontWeight();">

<script>
function changeFontWeight(){
	var obj1 = document.getElementById("list1");
	var obj2 = document.getElementById("list2");
	var obj3 = document.getElementById("list3");
	if(obj1.style.fontWeight == "bold"){
		obj1.style.fontWeight = "normal";
		obj2.style.fontWeight = "bold";
		list = "list2";
		

	} else if(obj2.style.fontWeight == "bold") {
		obj2.style.fontWeight = "normal";
		obj3.style.fontWeight = "bold";
		list = "list3";
	} else if(obj3.style.fontWeight == "bold"){
		obj3.style.fontWeight = "normal";
		obj1.style.fontWeight = "bold";
		list = "list1";
	} else {
		obj1.style.fontWeight = "bold";
		list = "list1";
	}
	var obj4 = document.getElementById(list).innerHTML;
	var title = document.getElementById("title");
	title.textContent = obj4
}
</script>


ボタンを押す度に、タイトルとfontWeightがboldに切り替わる。