PHP 获取今日天气
时间: 2023-02-09 09:36:21 浏览: 61
可以使用 PHP 的 CURL 库来访问天气 API,然后解析返回的 JSON 数据来获取今日天气信息。需要注意的是,需要先申请 API Key 才能使用天气 API。
以下是一个简单的示例:
```
<?php
// 设置 API Key
$apiKey = "YOUR_API_KEY";
// 设置城市
$city = "Beijing";
// 构造请求 URL
$url = "http://api.openweathermap.org/data/2.5/weather?q=" . $city . "&appid=" . $apiKey;
// 初始化 CURL
$ch = curl_init();
// 设置 CURL 选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 执行 CURL
$output = curl_exec($ch);
// 解析 JSON 数据
$weather = json_decode($output, true);
// 输出今日温度
echo "今日温度:" . $weather["main"]["temp"] . "K";
// 关闭 CURL
curl_close($ch);
?>
```
这只是一个简单的示例,具体用法还请参考 PHP 文档和天气 API 文档。
相关问题
php 获取天气接口
可以使用 PHP 的 cURL 库来请求天气接口。具体实现方法如下:
1. 初始化 cURL,设置相关请求参数。
2. 发送请求并获取响应。
3. 解析响应数据。
4. 使用解析出来的数据。
下面是一个简单的示例代码:
```
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://api.openweathermap.org/data/2.5/weather?q=beijing&appid=YOUR_APP_ID",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$data = json_decode($response, true);
// use data
}
?>
```
替换 `YOUR_APP_ID` 为自己申请的 API key。
需要注意的是,天气接口可能会有调用限制,需要在使用之前查看相关文档。
用PHP写一个获取当前天气的接口
可以使用以下代码获取当前天气的接口:
<?php
$city = "北京"; // 城市名
$url = "http://wthrcdn.etouch.cn/weather_mini?city=" . urlencode($city);
$json = file_get_contents($url);
$data = json_decode($json, true);
if ($data["status"] == 1000) {
$today = $data["data"]["forecast"][0];
$result = array(
"city" => $data["data"]["city"],
"date" => $today["date"],
"weather" => $today["type"],
"temperature" => $today["low"] . "~" . $today["high"],
"wind" => $today["fengxiang"] . $today["fengli"],
);
echo json_encode($result);
} else {
echo "获取天气信息失败!";
}
?>