OpenWeatherMap API で天気を Web サイトに表示する
OpenWeatherMap API を使うと、サイトに好きな都市のお天気を表示させられます。
API を使ったことがないので、練習を兼ねて記事を書きました。
こんな人におすすめです。
- API を触ったことがない
- HTML と CSS は使えるけど、他の言語は使えないから API 難しそう…
- WordPress を触ったことがあるのでなんとなく PHP がわかる人
準備編
必要なもの
- PHP を実行する環境(この記事では VSCode の拡張機能PHP Serverを使っています。)
- OpenWeatherMap API キー
- お好みのエディタ
①OpenWeatherMap API キーを取得する
-
OpenWeatherMapページにアクセスし、Sign in から新規会員登録
- 名前やメールアドレスを登録し、会員登録メールに記載の URL に飛ぶ
- ログイン成功
- API Keys から API キーをコピー、メモ帳などに貼り付けておく
②PHP で API キーを使う
取得した API キーを$apiKey
に入れて、天気を取得したい都市の名前を$city
に入れます。
今回は東京の現在の天気を表示してみましょう。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>お天気</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<?php
$apiKey = "ここに自分のAPIキー";
$city = "Tokyo";
$url = "https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey&units=metric&lang=ja";
$response = file_get_contents($url);
$data = json_decode($response, true);
?>
<h1>東京の天気予報</h1>
<p>
現在の天気:
<?php echo $data['weather'][0]['description']; ?>
</p>
<p>
気温:
<?php echo $data['main']['temp']; ?>°C
</p>
</body>
</html>
作った PHP ファイルの中で右クリック> Serve Project をすると、ページがブラウザで開きます。
PHP ファイルを更新しても自動反映されないので、なにか変更したらページをリロードしてください。
③ 応用:ユーザーが入力した都市の天気を表示する
先ほどは東京の天気しか取れませんでしたが、ユーザーが入力した都市の天気を表示させたいです。
入力欄に「Sapporo」と入れてみると、きちんと表示されます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>お天気</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>天気予報</h1>
<form method="get" action="">
<label for="city">都市名:</label>
<input type="text" id="city" name="city" required>
<button type="submit">確認</button>
</form>
<?php
if (isset($_GET['city'])) {
$city = htmlspecialchars($_GET['city']);
$apiKey = "ここに自分のAPIキー";
$url = "https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey&units=metric&lang=ja";
$response = file_get_contents($url);
$data = json_decode($response, true);
if ($data && $data['cod'] == 200) {
echo "<h2>" . htmlspecialchars($data['name']) . "の天気</h2>";
echo "<p>現在の天気: " . htmlspecialchars($data['weather'][0]['description']) . "</p>";
echo "<p>気温: " . htmlspecialchars($data['main']['temp']) . "°C</p>";
} else {
echo "<p>天気情報を取得できませんでした。</p>";
}
}
?>
</body>
</html>
解説
ユーザーが入力した都市名が、GET リクエストとして OpenWeatherMap API のサーバーに送られます。
<input type="text" id="city" name="city" required />
name="city"
と$_GET['city']
が紐づいています。
name="city"
で入力した値を$city
に代入します。htmlspecialchars()
はセキュリティ対策のために入れています。
$city = htmlspecialchars($_GET['city']);
$url
には$url = "https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey&units=metric&lang=ja"
が代入されており、URL の途中には$city
や$apiKey
が入っています。
手入力で URL をいじってアクセスすると、API の素の状態(JSON 形式のデータ)が見られます!
この JSON 形式のデータをjson_decode
で JSON を連想配列に変換し、Web ページに表示しやすいデータへ加工しています。
Discussion