array( 'method' => 'GET', 'header' => "User-Agent: PHP\r\n" ) )); $data = file_get_contents($url, false, $context); return $data; } $weatherData = array(); for ($i = 0; $i < count($cities); $i++) { $city = $cities[$i]; $url = "http://api.openweathermap.org/data/2.5/weather?id=$city&units=metric&cnt=7&lang=AR&appid=$apiKey"; $json = fetchWeatherData($url); // Check if the request was successful if ($json === FALSE) { continue; } $data = json_decode($json, true); if (isset($data['main']['temp']) && isset($data['weather'][0]['description']) && isset($data['weather'][0]['id'])) { $deg = (string) round($data['main']['temp']); $desc = $data['weather'][0]['description']; $icon = (string) $data['weather'][0]['id']; $weatherData['city'][] = array( 'deg' => $deg, 'name' => $names[$i], 'desc' => $desc, 'icon' => $icon ); } } header('Content-type: application/json'); echo json_encode($weatherData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); $fp = fopen($cachefile, 'w'); // Save the contents of output buffer to the file fwrite($fp, ob_get_contents()); // Close the file fclose($fp); // Send the output to the browser ob_end_flush(); ?>