LoginSignup
0
0

More than 3 years have passed since last update.

APIを使用して検索した首都の天気を表示させる

Last updated at Posted at 2020-07-10

はじめに

今回この記事を書く背景として、工場勤務からit企業へ転職し普段の業務でAPIを使用するので、自分が勉強した内容のアウトプットとなります。
ちなみに、転職して4ヶ月目になりますが、まだポンコツなのでこれからも記事を量産していくので、良かったらご指摘等あればご教示お願いします。

環境

ローカルサーバー:MAMP
OS:Mac
エディタ:VScode

APIとは

Application Programming Interface(アプリケーションプログラミングインタフェース)。
公開しているソフトウェアを他からをもってきてガッチャンこするイメージ。
外部のソフトウェアを使用する事により、効率的に開発が行えます。

今回のお天気APIを使用する手順

①APIを公開しているサイト(今回は下記URL)に登録。
https://openweathermap.org/

②ヘッダーにある「API」から「Current Weather Data」の「Subscribe」から無料枠を選んで、「APIkeys」からAPIkeyを発行する。

---ココからはエディタで作業します---

③APIkey+URLを使用しサイトのAPI(中身はjson形式のデータ)を取得

④jsonデータをエンコードし、検索した地域によって天気などを表示させる

APIkeyとは?

ざっくりいうと、キーなのでセキュリティに関わるものですね。
APIkeyは発行する事により、ユーザーを認証し、ある一定の条件をクリアしたユーザーのみにAPIを使う権限を与えるような感じ。

実践

index.php
<?php

    $weather = "";
    $error = "";

    //配列にcityがあるかの確認//
    if (array_key_exists('city', $_GET)) {
      $url_get=file_get_contents("https://api.openweathermap.org/data/2.5/weather?q=".$_GET['city'].",&appid=発行したAPIkey");
      $dateArrer=json_decode($url_get,true);
      $weather=$_GET['city']."の天気:".$dateArrer['weather'][0]['main'].",".$dateArrer['weather'][0]['description'];

    }


?>


<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags always come first -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">

      <title>Weather Scraper</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">

      <style type="text/css">

      html { 
          background: url(background.jpeg) no-repeat center center fixed; 
          -webkit-background-size: cover;
          -moz-background-size: cover;
          -o-background-size: cover;
          background-size: cover;
          }

          body {

              background: none;

          }

          .container {

              text-align: center;
              margin-top: 100px;
              width: 450px;

          }

          input {

              margin: 20px 0;

          }

          #weather {

              margin-top:15px;

          }

      </style>

  </head>
  <body>

      <div class="container">

          <h1>What's The Weather?</h1>



          <form>
  <fieldset class="form-group">
    <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']; 

      }

      ?>">
  </fieldset>

  <button type="submit" class="btn btn-primary">Submit</button>
</form>

          <div id="weather"><?php 

              if ($weather) {

                  echo '<div class="alert alert-success" role="alert">
  '.$weather.'
</div>';

              } else if ($error) {

                  echo '<div class="alert alert-danger" role="alert">
  '.$error.'
</div>';

              }

              ?></div>
      </div>

    <!-- jQuery first, then Bootstrap JS. -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
  </body>
</html>

デバッグ

デバッグは下記を使用しましょう。
print_r();
var_dump();
echoは詳細まで出力してくれないので、上記2つを使いましょう。
実際にデバックしてみましょう。

index.php

<?php

    $weather = "";
    $error = "";

    if (array_key_exists('city', $_GET)) {
      $url_get=file_get_contents("https://api.openweathermap.org/data/2.5/weather?q=".$_GET['city'].",&appid=発行したAPIkey");

      print_r($url_get);//←ここ
      $dateArrer=json_decode($url_get,true);
      $weather=$_GET['city']."の天気:".$dateArrer['weather'][0]['main'].",".$dateArrer['weather'][0]['description'];

    }


?>

結果.
{"coord":{"lon":139.69,"lat":35.69},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"stations","main":{"temp":300.86,"feels_like":304.4,"temp_min":299.15,"temp_max":302.04,"pressure":1010,"humidity":88},"visibility":10000,"wind":{"speed":4.6,"deg":190},"clouds":{"all":75},"dt":1594364963,"sys":{"type":1,"id":8077,"country":"JP","sunrise":1594323209,"sunset":1594375158},"timezone":32400,"id":1850144,"name":"Tokyo","cod":200}

このハッシュで囲まれてるデータがJSON形式のデータとなります。
PHPでJSONデータをそのまま扱う事ができないので、json_decodeで
JSONデータを配列に変換します。

$dateArrer=json_decode($url_get,true);

結果

index.php
print_r($dateArrer);
Array ( [coord] => Array ( [lon] => 139.69 [lat] => 35.69 ) [weather] => Array ( [0] => Array ( [id] => 803 [main] => Clouds [description] => broken clouds [icon] => 04d ) ) [base] => stations [main] => Array ( [temp] => 300.86 [feels_like] => 301.97 [temp_min] => 299.82 [temp_max] => 301.48 [pressure] => 1010 [humidity] => 83 ) [visibility] => 10000 [wind] => Array ( [speed] => 7.2 [deg] => 170 ) [clouds] => Array ( [all] => 75 ) [dt] => 1594365866 [sys] => Array ( [type] => 1 [id] => 8063 [country] => JP [sunrise] => 1594323209 [sunset] => 1594375158 ) [timezone] => 32400 [id] => 1850144 [name] => Tokyo [cod] => 200 )

見事json_decode()で配列化に成功しました。
あとは欲しい情報をここから取ってくるだけです。

index.php
$weather=$_GET['city']."の天気:".$dateArrer['weather'][0]['main'].",".$dateArrer['weather'][0]['description'];
//$dateArrerの中の
//[weather]の[0]の[main]で天気が表示できます。

まとめ

今回はお天気APIを使用して、検索した首都の天気を表示させました。
JSONについて詳しく知りたい方は下記URLを閲覧してみてください。
https://reffect.co.jp/html/what_is_json

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0