options->sidebarBlock) && in_array('ShowSidebarWeather', $this->options->sidebarBlock) && ! $this->is('post')): ?> options->weatherCity ?: 'Beijing'); $apiKey = trim($this->options->weatherApiKey ?: ''); $cacheFile = dirname(__DIR__, 2) . '/assets/weather_cache.json'; // 缓存机制:记录城市和时间,过期 1 小时,城市变更时自动失效 function hh_fetch_weather($city, $apiKey, $cacheFile) { if (file_exists($cacheFile)) { $raw = @file_get_contents($cacheFile); $cached = $raw ? json_decode($raw, true) : null; // 缓存结构:{"city":"xxx","timestamp":12345678,"data":{…}} if ($cached && isset($cached['city'], $cached['timestamp'], $cached['data'])) { if ($cached['city'] === $city && time() - $cached['timestamp'] < 3600) { return $cached['data']; } } } if (empty($apiKey) || empty($city)) { return null; } $url = 'https://api.openweathermap.org/data/2.5/weather?q=' . urlencode($city) . '&appid=' . $apiKey . '&units=metric&lang=zh_cn'; $json = @file_get_contents($url); if ($json) { $payload = json_encode([ 'city' => $city, 'timestamp' => time(), 'data' => json_decode($json, true), ]); @file_put_contents($cacheFile, $payload); return json_decode($json, true); } return null; } $weather = hh_fetch_weather($city, $apiKey, $cacheFile); // 用于调试:在 HTML 注释中输出参数和值,方便查看 $reqUrl = 'https://api.openweathermap.org/data/2.5/weather?q=' . urlencode($city) . '&appid=' . $apiKey . '&units=metric&lang=zh_cn'; ?>
'北京', 'Guangzhou' => '广州', 'Shenzhen' => '深圳', 'Shanghai' => '上海', 'Chengdu' => '成都', // 可根据需要继续添加 ]; if (isset($map[$inputCity])) { return $map[$inputCity]; } if (isset($map[$weather['name']])) { return $map[$weather['name']]; } return $weather['name']; } $displayCity = hh_display_city($city, $weather); $w = $weather['weather'][0]; $m = $weather['main']; $wind = $weather['wind'] ?? []; $iconUrl = 'https://openweathermap.org/img/wn/' . $w['icon'] . '@2x.png'; ?>
<?php echo htmlspecialchars($w['description'], ENT_QUOTES); ?>

°C

体感:°C;湿度:%;气压: hPa

风速: m/s

天气接口错误:

天气获取失败