OpenWeatherMap Forecast Min/Max Temperature Hole Day Forecast

Viewed 24

I try to use the foreach loop to display only the next min. and max. (of whole day) temperatures for the next 3 days. But I can only read them out so that it gives me min. max. Temperatures in 3h interval for the actual and the coming 4 days.

But it should be like this:
Thursday 15.09: Max: 25°C/Min: 20°C
Friday 16.09: Max: 23°C/Min: 14°C
Saturday 17.09: Max: 20°C/Min: 10°C

$api_forecast   = 'https://api.openweathermap.org/data/2.5/forecast?q=berlin,DE,DE&appid='.$api_key;
$forecast_data  = json_decode( file_get_contents($api_forecast),  true);
echo '<table><tbody>';

foreach ($forecast_data['list'] as $val) {
  $f_temp         = round($val['main']['day'] - 273.15) . '°C';
  $f_date         = date($dateFormat , strtotime($val['dt_txt']));
  $f_pressure     = $val['pressure'];
  $f_humidity     = $val['humidity'];
  $f_wind_speed   = $val['wind']['speed'];
  $f_wind_dir     = $val['wind']['deg'];
  $f_clouds       = $val['clouds']['all'];
  $f_weather      = $val['weather'][0];
  $f_main         = $val['main'];
  $f_icon         = $val['icon'];
  $f_max_temp     = round($val['main']['temp_max'] - 273.15) . '°C';
  $f_min_temp     = round($val['main']['temp_min'] - 273.15) . '°C';

  echo  '<tr><td><strong>' . $f_date . ':</strong></td><td>Max:' .  $f_max_temp . '</td><td>/Min:' .  $f_min_temp . '</td></tr>';
}

echo '</tbody></table>';
1 Answers

With the right parameters when calling the Openweathermap API, you can save yourself a lot of work ( more ).

$maxDays = 3;
$query = http_build_query(array(
  'q' => 'Berlin,DE,DE',
  'cnt' => $maxDays,
  'mode' => 'json',
  'units' => 'metric',
  'lang' => 'de',
  'appid' => $apiId,
));
$url = 'https://api.openweathermap.org/data/2.5/forecast/daily?'.$query;
$json = file_get_contents($url);

You get your temperatures by the day in a form that you can easily output:

  //:
  'list' => 
  array (
    0 => 
    array (
      'dt' => 1663239600,
      'sunrise' => 1663216817,
      'sunset' => 1663262596,
      'temp' => 
      array (
        'day' => 15.48,
        'min' => 12.62,
        'max' => 18.45,
        'night' => 12.78,
        'eve' => 16.02,
        'morn' => 13.19,
      ),
Related