✅ PHP API requests (cURL)
✅ JSON data handling
✅ Form processing
✅ Basic error handling
✅ Simple UI with CSS
Register at OpenWeatherMap for a free API key
config.php
(API Configuration)<?php
define('API_KEY', 'your_api_key_here');
define('BASE_URL', 'https://api.openweathermap.org/data/2.5/weather');
?>
index.php
(Main Application)<?php
require 'config.php';
$weather = [];
$error = '';
if (isset($_GET['city'])) {
$city = urlencode($_GET['city']);
$url = BASE_URL . "?q={$city}&appid=" . API_KEY . "&units=metric";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if ($data['cod'] == 200) {
$weather = [
'city' => $data['name'],
'temp' => round($data['main']['temp']),
'humidity' => $data['main']['humidity'],
'wind' => $data['wind']['speed'],
'description' => ucfirst($data['weather'][0]['description']),
'icon' => $data['weather'][0]['icon']
];
} else {
$error = "City not found. Please try again.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Simple Weather App</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 0 auto;
padding: 20px;
text-align: center;
}
.weather-card {
background: #f0f8ff;
border-radius: 10px;
padding: 20px;
margin-top: 20px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
.error { color: red; }
.weather-icon {
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<h1>Weather App</h1>
<form method="GET">
<input type="text" name="city" placeholder="Enter city name" required>
<button type="submit">Get Weather</button>
</form>
<?php if ($error): ?>
<p class="error"><?php echo $error; ?></p>
<?php elseif (!empty($weather)): ?>
<div class="weather-card">
<h2><?php echo $weather['city']; ?></h2>
<img src="https://openweathermap.org/img/wn/<?php echo $weather['icon']; ?>@2x.png"
alt="<?php echo $weather['description']; ?>" class="weather-icon">
<p><strong><?php echo $weather['description']; ?></strong></p>
<p>Temperature: <?php echo $weather['temp']; ?>°C</p>
<p>Humidity: <?php echo $weather['humidity']; ?>%</p>
<p>Wind: <?php echo $weather['wind']; ?> m/s</p>
</div>
<?php endif; ?>
</body>
</html>
your_api_key_here
in config.php