<?php // Endpoint Open-Meteo per Grosseto (2 giorni di previsione oraria) $url = "https://api.open-meteo.com/v1/forecast?latitude=42.76&longitude=11.11&hourly=temperature_2m,relative_humidity_2m,weather_code&forecast_days=2&timezone=Europe/Rome"; // 1. Inizializzazione cURL $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 5); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); curl_close($ch); // 2. Controllo errori di connessione if ($response === false) { die("Errore nella chiamata cURL: " . $curlError); } if ($httpCode !== 200) { die("L'API ha risposto con codice HTTP: " . $httpCode); } // 3. Decodifica JSON $data = json_decode($response, true); if ($data === null) { die("Errore nella decodifica del JSON."); } // Funzione di supporto per tradurre i codici WMO dell'API function decodificaMeteoCode(int $code): string { return match ($code) { 0 => "Cielo sereno ☀️", 1, 2, 3 => "Prevalentemente sereno / Nuvoloso ⛅", 45, 48 => "Nebbia 🌫️", 51, 53, 55 => "Pioggerella 🌧️", 61, 63, 65 => "Pioggia 🌧️", 71, 73, 75 => "Neve ❄️", 80, 81, 82 => "Rovesci di pioggia 🌦️", 95, 96, 99 => "Temporale 🌩️", default => "Codice sconosciuto ($code)" }; } // Estrazione degli array orari $orari = $data['hourly']['time']; $temperature = $data['hourly']['temperature_2m']; $umidita = $data['hourly']['relative_humidity_2m']; $codiciMeteo = $data['hourly']['weather_code']; ?> <!DOCTYPE html> <html lang="it"> <head> <meta charset="UTF-8"> <title>Test API Open-Meteo</title> <style> body { font-family: Arial, sans-serif; margin: 20px; background-color: #f4f4f9; } table { border-collapse: collapse; width: 100%; max-width: 800px; background: #fff; } th, td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; } th { background-color: #007bff; color: white; } tr:nth-child(even) { background-color: #f9f9f9; } </style> </head> <body> <h2>Previsioni Orarie Grosseto (48 ore)</h2> <p><strong>Unità di misura:</strong> Temperatura (°C), Umidità (%)</p> <table> <thead> <tr> <th>Data e Ora</th> <th>Meteo</th> <th>Temperatura (°C)</th> <th>Umidità (%)</th> </tr> </thead> <tbody> <?php // Ciclo sugli array paralleli restituite dall'API $totaleOre = count($orari); for ($i = 0; $i < $totaleOre; $i++): // Formattazione data/ora per renderla più leggibile (da YYYY-MM-DDTHH:mm a DD/MM/YYYY HH:mm) $dataFormattata = date("d/m/Y H:i", strtotime($orari[$i])); ?> <tr> <td><?= $dataFormattata ?></td> <td><?= decodificaMeteoCode($codiciMeteo[$i]) ?></td> <td><?= $temperature[$i] ?> °C</td> <td><?= $umidita[$i] ?> %</td> </tr> <?php endfor; ?> </tbody> </table> </body> </html>
You have javascript disabled. You will not be able to edit any code.