php调用天气接口的代码,php调用API接口查询天气功能的方法介绍
时间: 2024-06-08 21:09:35 浏览: 10
以下是一个简单的PHP调用天气接口的代码:
```php
$city = '北京'; // 查询城市名称
$url = 'http://wthrcdn.etouch.cn/weather_mini?city='.urlencode($city); // 天气查询接口url
$data = file_get_contents($url); // 获取接口返回的数据
$result = json_decode($data, true); // 将json格式的数据转换为数组
if ($result['status'] == 1000) { // 判断接口返回的状态码是否为1000,1000表示成功
$weather = $result['data']['forecast'][0]['type']; // 获取今天天气情况
$temp = $result['data']['wendu']; // 获取当前温度
echo $city.'今天的天气是'.$weather.',当前温度为'.$temp.'℃';
} else {
echo '查询失败';
}
```
这段代码使用了ETOUCH天气查询API,其中`$city`变量存储要查询的城市名称,使用`urlencode()`函数对城市名称进行编码,然后将城市名称拼接到API的URL中,使用`file_get_contents()`函数获取接口返回的数据,再使用`json_decode()`函数将json格式的数据转换为数组,最后从数组中获取需要的数据。
这只是一个简单的例子,实际应用中还需要对返回的数据进行错误处理和格式化等操作。
建议在使用第三方天气查询API时,先了解其API文档,了解返回的数据格式和状态码含义,以便更好地使用API。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)