LoginSignup
0
0

More than 1 year has passed since last update.

【PHP】Open Weather Map APIから気象情報を取得してみた

Last updated at Posted at 2021-10-26

初めに

ダッシュボード作成のために、気象情報をAPIにて取得する
Open Weather Map APIを使用すると取得できることが判明
⇒PHPを用い、HP等で表示させる用途を想定

環境

  • Windows10
  • PHP 8.0.6

パラメータ

lat (float):必須、取得したい場所の緯度、
lng (float): 必須、取得したい場所の経度
appid:必須、Open Weather Map APIに登録し、取得してください。
unit:metric 摂氏温度(℃)の取得に固定しています。
lang:ja 日本語に固定しています。

本コードではweather_configにてパラメータをセットしてください。

コード

owm_api.php
<?php
//Open Weather Map気象情報を取得する
//パラメータをセット
$weather_config = array(
    'appid' => 'XXXXXXXXXXXXXXXXXXXXX',
    'lat' => '35.0000000',
    'lon' => '135.0000000',
);
$weather_json = file_get_contents('http://api.openweathermap.org/data/2.5/weather?lat=' . $weather_config['lat'] . '&lon=' . $weather_config['lon'] . '&units=metric&lang=ja&APPID=' . $weather_config['appid']);
$weather_array = json_decode($weather_json, true);

//必要情報を変数に格納
$weather = $weather_array["weather"]["0"]["main"];
$temp = $weather_array["main"]["temp"];
$temp_min = $weather_array["main"]["temp_min"];
$temp_max = $weather_array["main"]["temp_max"];
$cloud = $weather_array["clouds"]["all"];

echo "天気" . $weather . "\n";
echo "気温:" . $temp . "\n";
echo "最低気温:" . $temp_min . "\n";
echo "最高気温:" . $temp_max . "\n";
echo "雲量:" . $cloud . "\n";

参考サイト

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