weather_app_code
weather_app_code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; padding: 20px; }
.container { max-width: 400px; margin: auto; padding: 20px; border: 1px solid #ddd; border-radius: 10px; }
input { padding: 10px; width: 80%; margin-bottom: 10px; }
button { padding: 10px; cursor: pointer; }
.weather-info { margin-top: 20px; }
</style>
</head>
<body>
<div class="container">
<h2>Weather Application</h2>
<input type="text" id="city" placeholder="Enter city name">
<button onclick="getWeather()">Get Weather</button>
<div class="weather-info" id="weather-info"></div>
</div>
<script>
function getWeather() {
let city = document.getElementById('city').value;
if (city === '') {
alert('Please enter a city name');
return;
}
fetch('weather.php?city=' + city)
.then(response => response.json())
.then(data => {
if (data.error) {
document.getElementById('weather-info').innerHTML = '<p>' + data.error + '</p>';
} else {
document.getElementById('weather-info').innerHTML = `
<h3>${data.city}, ${data.country}</h3>
<p>Temperature: ${data.temp}°C</p>
<p>Weather: ${data.weather}</p>
<h4>3-Day Forecast</h4>
${data.forecast.map(day => `<p>${day.date}: ${day.temp}°C, ${day.weather}</p>`).join('')}
`;
}
});
}
</script>
</body>
</html>
# weather.php (Backend API Fetching)
<?php
header('Content-Type: application/json');
if (empty($city)) {
echo json_encode(["error" => "City name is required"]);
exit;
}
$apiUrl = "https://api.openweathermap.org/data/2.5/weather?q={$city}&units=metric&appid={$apiKey}";
$forecastUrl = "https://api.openweathermap.org/data/2.5/forecast?q={$city}&units=metric&cnt=3&appid={$apiKey}";
$weatherData = file_get_contents($apiUrl);
$forecastData = file_get_contents($forecastUrl);
$response = [
"city" => $weatherArray['name'],
"country" => $weatherArray['sys']['country'],
"temp" => $weatherArray['main']['temp'],
"weather" => $weatherArray['weather'][0]['description'],
"forecast" => []
];
echo json_encode($response);
?>