您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。