Robinit

IT関連メモ

PHPで天気情報APIのOpenWeatherMapを使う

ユーザが都市名を入力すると天気情報APIのOpenWeatherMapを使い、
現在の天気を表示するWebアプリをPHPで作成する。
f:id:wonder_three:20180203234119p:plain

はじめに

天気情報を取得するためにOpenWeatherMapのAPIを利用するが、
利用するにはユーザ登録が必要。

OpenWeatherMapにアクセスし、ユーザー登録を行う
openweathermap.org

ユーザ登録すれば、APIを利用するのに必要な、
API Keyが発行されるので、それをメモしておく。

コード

先にコードを記載する。

<?php
        $weather = "";
        if (array_key_exists('city', $_GET)) {
            $urlContents = file_get_contents("http://api.openweathermap.org/data/2.5/weather?q=".$_GET['city']."&appid=XXXXXXXXXXXXXXXXXXXXXXXXX");    //appidにはAPI Keyを入れる
            
            $weatherArray = json_decode($urlContents, true);    //連想配列の場合は第2引数へtrueを指定
            //print_r($weatherArray);
            $weather = $_GET['city']."'s Weather:".$weatherArray['weather'][0]['main'].",".$weatherArray['weather'][0]['description'];
        }
?>
    <h1>What's The Weather?</h1>
    <form>
        <label for="city">Enter the name of a city.</label>
        <input type="text" class="form-control" name="city" id="city" placeholder="Eg. London, Tokyo" value="<?php if (array_key_exists('city', $_GET)) {
                echo $_GET['city']; }?>">
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
    <?php 
        if ($weather) {
              echo '<div class="alert alert-success" role="alert">'.$weather.'</div>';
        }
    ?>

天気情報APIのOpenWeatherMapを使う

今回は簡単に実装するため、file_get_contents()にAPIを渡す
appidにはユーザ登録で取得したAPI Keyを渡す
※file_get_contents()にAPIを渡す場合、
 タイムアウトが設定通り動かない、リクエストが失敗した場合は、過去の成功したヘッダ情報を返してしまう
 などの問題があるので注意が必要。

$urlContents = file_get_contents("http://api.openweathermap.org/data/2.5/weather?q=".$_GET['city']."&appid=XXXXXXXXXXXXXXXXXXXXXXXXX"); 

次に返ってきたJSONjson_decode()を使い配列に入れてユーザに通知する。

$weatherArray = json_decode($urlContents, true); 

今回は現在の天気とその詳細を表示するだけですが、
返ってきたJSONの中に最高/最低気温や湿度などの情報もある
また5日間の天気予報情報を取得できるAPIもあるので、色々と使ってみたい。