制作一个天气查询系统需要完成以下步骤:
-
获取天气数据接口:首先需要找到一个可以获取天气数据的 API 接口,常用的免费接口有 OpenWeatherMap、和风天气等。
-
确定数据格式:接口返回的数据格式可能是 JSON 或 XML 格式,需要先确定数据格式并进行解析。
-
编写代码:通过 PHP 代码调用接口获取天气数据并将其解析后展示到页面上。
-
前端设计:将天气数据以图表、表格等方式进行展示,并进行美化。
以下是具体实现步骤:
- 获取天气数据接口
我们使用 OpenWeatherMap 提供的 API 接口,通过访问接口地址就可以获取到一些基本的天气数据:
http://api.openweathermap.org/data/2.5/weather?q={城市名}&appid={APPID}
其中,{城市名} 是要查询的城市名,{APPID} 是注册 OpenWeatherMap 后分配的 API 密钥。
- 确定数据格式
通过访问 API 接口,可以得到一个 JSON 格式的数据,具体格式如下:
{
"coord": {
"lon": -122.08,
"lat": 37.39
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 282.55,
"feels_like": 281.86,
"temp_min": 280.37,
"temp_max": 284.26,
"pressure": 1023,
"humidity": 100
},
"visibility": 16093,
"wind": {
"speed": 1.5,
"deg": 350
},
"clouds": {
"all": 1
},
"dt": 1560350645,
"sys": {
"type": 1,
"id": 5122,
"message": 0.0139,
"country": "US",
"sunrise": 1560343627,
"sunset": 1560396563
},
"timezone": -25200,
"id": 420006353,
"name": "Mountain View",
"cod": 200
}
- 编写代码
通过 PHP 代码访问 OpenWeatherMap 的 API 接口,并将 JSON 数据解析成 PHP 数组对象。
<?php
// 定义城市名和 API 密钥
$city = 'beijing';
$apikey = '1234567890';
// 获取 API 数据
$data = file_get_contents('http://api.openweathermap.org/data/2.5/weather?q='.$city.'&appid='.$apikey);
// 解析 JSON 数据
$weather = json_decode($data, true);
// 输出天气信息
echo $weather['name'].'天气:'.$weather['weather'][0]['description'];
echo '<br>温度:'.($weather['main']['temp'] - 273.15).'℃';
echo '<br>湿度:'.$weather['main']['humidity'].'%';
- 前端设计
将 PHP 代码嵌入到 HTML 页面中,通过 CSS 进行美化,可以得到最终的天气查询页面。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>天气查询系统</title>
<style>
#result {
border: 1px solid #ddd;
padding: 10px;
margin-top: 20px;
}
table {
border-collapse: collapse;
}
td, th {
border: 1px solid #ddd;
padding: 5px;
}
</style>
</head>
<body>
<h1>天气查询系统</h1>
<form action="" method="post">
<input type="text" name="city" placeholder="请输入要查询的城市名">
<input type="submit" value="查询">
</form>
<?php
if (!empty($_POST['city'])) {
// 获取城市名和 API 密钥
$city = $_POST['city'];
$apikey = '1234567890';
// 获取 API 数据
$data = file_get_contents('http://api.openweathermap.org/data/2.5/weather?q='.$city.'&appid='.$apikey);
// 解析 JSON 数据
$weather = json_decode($data, true);
?>
<div id="result">
<h2><?php echo $weather['name']; ?>天气</h2>
<table>
<tr>
<th>温度</th>
<th>湿度</th>
<th>天气</th>
<th>风速</th>
</tr>
<tr>
<td><?php echo ($weather['main']['temp'] - 273.15); ?>℃</td>
<td><?php echo $weather['main']['humidity']; ?>%</td>
<td><?php echo $weather['weather'][0]['description']; ?></td>
<td><?php echo $weather['wind']['speed']; ?>米/秒</td>
</tr>
</table>
</div>
<?php } ?>
</body>
</html>
以上就是用 PHP 制作一个天气查询系统的全过程。