在Yii中集成天气查询服务,你可以选择一些流行的天气API,例如OpenWeatherMap、Weatherstack等。下面以OpenWeatherMap为例,介绍如何在Yii中集成天气查询服务。
首先,注册一个OpenWeatherMap帐户并获取API密钥(APPID)。
创建一个新的Yii项目(如果你还没有一个):
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
php yii generate controller Weather
WeatherController
,添加一个action来处理天气查询请求:<?php
namespace app\controllers;
use yii\web\Controller;
class WeatherController extends Controller
{
public function actionIndex($city)
{
$api_key = 'your_openweathermap_api_key';
$url = "http://api.openweathermap.org/data/2.5/weather?q={$city}&appid={$api_key}";
$response = file_get_contents($url);
$data = json_decode($response, true);
if ($data['cod'] != 200) {
return $this->render('error', [
'message' => $data['message'],
]);
}
return $this->render('index', [
'data' => $data,
]);
}
}
views/weather/index.php
和 views/weather/error.php
。views/weather/index.php
示例:
<?php
/* @var $this yii\web\View */
/* @var $data array */
$this->title = "Weather in " . $data['name'];
?>
<h1>Weather in <?php echo $data['name']; ?></h1>
<p>Temperature: <?php echo $data['main']['temp'] - 273.15; ?> °C</p>
<p>Humidity: <?php echo $data['main']['humidity']; ?> %</p>
<p>Wind Speed: <?php echo $data['wind']['speed']; ?> m/s</p>
<p>Weather Description: <?php echo $data['weather'][0]['description']; ?></p>
views/weather/error.php
示例:
<?php
/* @var $this yii\web\View */
/* @var $message string */
$this->title = "Error";
?>
<h1>Error</h1>
<p><?php echo $message; ?></p>
config/web.php
中添加路由规则:'urlManager' => [
// ...
'rules' => [
'' => 'weather/index',
'error' => 'weather/error',
],
],
现在,你可以通过访问http://your-domain.com/weather/your-city
来查询指定城市的天气信息。请确保将your_openweathermap_api_key
替换为你自己的OpenWeatherMap API密钥。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。