Hi! Could we please enable some services and cookies to improve your experience and our website?

SQLize | PHPize | SQLtest

Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code

A A A
Login    Share code      Blog   FAQ
Copy Format Clear
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Simple PHP Weather Forecast</title> <style> body { font-family: Arial, sans-serif; background: #e0f7fa; max-width: 600px; margin: 40px auto; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px #00796b; } h1 { text-align: center; color: #004d40; } form { text-align: center; margin-bottom: 20px; } input[type="text"] { padding: 10px; font-size: 16px; width: 70%; border: 1px solid #00796b; border-radius: 5px; } button { padding: 10px 15px; font-size: 16px; background: #00796b; color: white; border: none; border-radius: 5px; cursor: pointer; margin-left: 10px; } .weather-result { background: white; border-radius: 8px; padding: 20px; box-shadow: 0 0 8px #004d40; } .weather-result h2 { margin-top: 0; margin-bottom: 10px; color: #00796b; } .error { color: red; text-align: center; } </style> </head> <body> <h1>Simple PHP Weather Forecast</h1> <form method="post"> <input type="text" name="city" placeholder="Enter city name" required value="<?php echo isset($_POST['city']) ? htmlspecialchars($_POST['city']) : ''; ?>" /> <button type="submit">Get Weather</button> </form> <?php if ($_SERVER["REQUEST_METHOD"] === "POST") { $city = trim($_POST['city']); $apiKey = "YOUR_API_KEY"; // Replace with your OpenWeatherMap API key $apiUrl = "https://api.openweathermap.org/data/2.5/weather?q=".urlencode($city)."&appid=".$apiKey."&units=metric"; // Fetch weather data from API $json = @file_get_contents($apiUrl); if ($json === FALSE) { echo '<p class="error">Unable to retrieve weather data. Please try again later.</p>'; } else { $data = json_decode($json, true); if ($data['cod'] == 200) { $cityName = htmlspecialchars($data['name']); $temp = $data['main']['temp']; $desc = ucfirst($data['weather'][0]['description']); $humidity = $data['main']['humidity']; $windSpeed = $data['wind']['speed']; echo '<div class="weather-result">'; echo "<h2>Weather in $cityName</h2>"; echo "<p><strong>Temperature:</strong> $temp &deg;C</p>"; echo "<p><strong>Condition:</strong> $desc</p>"; echo "<p><strong>Humidity:</strong> $humidity %</p>"; echo "<p><strong>Wind Speed:</strong> $windSpeed m/s</p>"; echo "</div>"; } else { echo '<p class="error">City not found. Please enter a valid city name.</p>'; } } } ?> </body> </html>

Stuck with a problem? Got Error? Ask AI support!

Copy Clear