您好,登錄后才能下訂單哦!
在Yii中集成天氣查詢服務(wù),你可以選擇一些流行的天氣API,例如OpenWeatherMap、Weatherstack等。下面以O(shè)penWeatherMap為例,介紹如何在Yii中集成天氣查詢服務(wù)。
首先,注冊一個OpenWeatherMap帳戶并獲取API密鑰(APPID)。
創(chuàng)建一個新的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
中添加路由規(guī)則:'urlManager' => [
// ...
'rules' => [
'' => 'weather/index',
'error' => 'weather/error',
],
],
現(xiàn)在,你可以通過訪問http://your-domain.com/weather/your-city
來查詢指定城市的天氣信息。請確保將your_openweathermap_api_key
替換為你自己的OpenWeatherMap API密鑰。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。