PHP code example of zhaiyuxin / weather

1. Go to this page and download the library: Download zhaiyuxin/weather library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

zhaiyuxin / weather example snippets


'weather' => [
    'key' => env('WEATHER_API_KEY'),
],



use Yuxin\Weather\Weather;

// 创建实例
$weather = new Weather('your_api_key');

// 获取基础天气信息
$response = $weather->getWeather('北京');

// 获取详细天气信息
$response = $weather->getWeather('北京', 'forecast');

// 获取 XML 格式响应
$response = $weather->getWeather('北京', 'live', 'xml');



namespace App\Http\Controllers;

use Yuxin\Weather\Weather;

class WeatherController extends Controller
{
    public function index(Weather $weather)
    {
        // 获取北京天气
        $weather = $weather->getWeather('北京');

        return view('weather.index', compact('weather'));
    }
}



use Yuxin\Weather\Facades\Weather;

// 获取天气信息
$weather = Weather::getWeather('广州');



use Yuxin\Weather\Weather;

$weather = new Weather('your_api_key');

// 设置超时时间
$weather->setGuzzleOptions(['timeout' => 30]);

// 设置代理
$weather->setGuzzleOptions([
    'proxy' => 'http://proxy.example.com:8080',
    'timeout' => 60,
    'verify' => false
]);



use Yuxin\Weather\Weather;
use Illuminate\Support\Facades\Log;
use Yuxin\Weather\Exceptions\HttpException;
use Yuxin\Weather\Exceptions\InvalidArgumentException;

try {
    $weather = new Weather('invalid_key');
    $response = $weather->getWeather('北京');
} catch (InvalidArgumentException $e) {
    // 处理参数错误
    Log::error('参数错误: ' . $e->getMessage());
} catch (HttpException $e) {
    // 处理 HTTP 请求错误
    Log::error('请求错误: ' . $e->getMessage());
}
json
{
  "status": "1",
  "count": "1",
  "info": "OK",
  "infocode": "10000",
  "forecasts": [
    {
      "city": "北京",
      "adcode": "110100",
      "province": "北京市",
      "reporttime": "2025-01-20 10:00:00",
      "casts": [
        {
          "date": "2025-01-20",
          "week": "1",
          "dayweather": "晴",
          "nightweather": "晴",
          "daytemp": "5",
          "nighttemp": "-5",
          "daywind": "北风",
          "nightwind": "北风",
          "daypower": "3",
          "nightpower": "3"
        }
      ]
    }
  ]
}