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'; ?>