用php写一个能获取天气的页面
以下是一个简单的PHP获取天气信息的页面示例:
<!DOCTYPE html>
<html>
<head>
<title>获取天气</title>
</head>
<body>
<h1>获取天气</h1>
<form method="post">
<label for="city">城市:</label>
<input type="text" id="city" name="city">
<button type="submit">查询</button>
</form>
<hr>
<?php
if(isset($_POST['city'])){
$city = $_POST['city'];
$weather_url = "https://api.openweathermap.org/data/2.5/weather?q=$city&appid=YOUR_APP_ID&units=metric";
$weather_data = json_decode(file_get_contents($weather_url));
if($weather_data->cod == 200){
$weather = $weather_data->weather[0]->description;
$temp = $weather_data->main->temp;
$humidity = $weather_data->main->humidity;
$wind_speed = $weather_data->wind->speed;
echo "<h2>$city 的天气情况</h2>";
echo "<p>天气:$weather</p>";
echo "<p>温度:$temp °C</p>";
echo "<p>湿度:$humidity %</p>";
echo "<p>风速:$wind_speed m/s</p>";
} else {
echo "<p>查询失败,请检查城市名称是否正确</p>";
}
}
?>
</body>
</html>
在这个示例中,我们使用OpenWeatherMap提供的API来获取天气信息。首先,用户需要在表单中输入城市名称并提交。然后,我们使用file_get_contents()函数来获取API的JSON数据,并使用json_decode()函数将其转换为PHP对象。如果查询成功,我们将从对象中提取所需的信息,并在页面上显示。否则,我们将显示一条错误消息。
请注意,上述示例中的YOUR_APP_ID是需要替换为您的OpenWeatherMap API密钥的地方。您可以从OpenWeatherMap的网站上免费注册并获取API密钥。
原文地址: https://www.cveoy.top/t/topic/Cv7 著作权归作者所有。请勿转载和采集!