前言
“好的内容需要好的呈现”—— 搭建 Typecho 博客时,单纯的文字难免显得单调。今天分享30个有趣又实用的公开 API,让你的页面鲜活起来。
一、API 是什么?为什么能让博客变生动?
简单说,API 就像 “数据的搬运工”—— 它能从其他平台(比如 QQ 空间、微博、抖音)获取实时数据,再展示到你的博客上。比如通过 QQ 音乐 API,访客能看到你正在听的歌;通过微博热搜 API,博客能同步实时热点,就像给博客 “装了个动态数据窗口”,让静态页面有了互动感和新鲜感。
这些 API 都不用复杂开发,复制代码稍作修改就能用。
二、实用 API 分享
1. QQ 等级显示API
这个 API 通过 QQ 空间公开接口获取等级信息,并在博客中展示:
// 在sidebar.php或自定义页面中添加
function getQQLevel($qq) {
$url = "https://r.qzone.qq.com/fcg-bin/cgi_get_score.fcg?mask=7&uins=".$qq;
$data = file_get_contents($url);
$data = mb_convert_encoding($data, "UTF-8", "GBK");
preg_match('/lvtext:"(\d+级)"/', $data, $level);
return isset($level[1]) ? $level[1] : '获取失败';
}
$qq = '你的QQ号'; // 替换成自己的QQ号
echo '我的QQ等级: '.getQQLevel($qq);
2. QQ 音乐状态 API
这个 API 会获取实时播放状态,展示您正在听的QQ音乐歌曲信息:
function getQQMusicStatus($qq) {
// QQ音乐状态获取
$url = "https://c.y.qq.com/rsc/fcgi-bin/fcg_get_profile_homepage.fcg?format=json&inCharset=utf-8&outCharset=utf-8¬ice=0&platform=yqq&uin=".$qq;
$context = stream_context_create([
'http' => [
'header' => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
]
]);
$data = json_decode(file_get_contents($url, false, $context), true);
// 判断是否有正在收听的歌曲
if (isset($data['data']['listen']) && !empty($data['data']['listen']['now'])) {
return [
'status' => true,
'song_name' => $data['data']['listen']['now']['song_name'],
'singer' => $data['data']['listen']['now']['singer'][0]['name'],
'cover' => $data['data']['listen']['now']['cover']
];
} else {
return [
'status' => false
];
}
}
$qq = '你的QQ号'; // 替换成自己的QQ号
$music = getQQMusicStatus($qq);
if ($music['status']) {
echo '<div class="qq-music">';
echo '<h3>我正在听</h3>';
echo '<img src="'.$music['cover'].'" style="width:60px;height:60px;float:left;margin-right:10px;" />';
echo '<div style="margin-left:70px;">';
echo '<p style="margin:0;"><strong>'.$music['song_name'].'</strong></p>';
echo '<p style="margin:0;color:#999;">- '.$music['singer'].'</p>';
echo '</div>';
echo '<div style="clear:both;"></div>';
echo '</div>';
} else {
echo '暂无音乐播放记录';
}
3.哔哩哔哩UP主数据API
展示您的B站粉丝数、视频数、播放量等数据。
<?php
function getBiliStats($uid) {
$url = "https://api.bilibili.com/x/relation/stat?vmid=".$uid."&jsonp=jsonp";
$data = json_decode(file_get_contents($url), true);
return $data['data'];
}
$uid = '你的B站UID';
$stats = getBiliStats($uid);
echo "粉丝数: ".$stats['follower'];
?>
4.GitHub贡献统计API
在博客上展示您的GitHub贡献图表。
<img src="https://ghchart.rshah.org/用户名" alt="GitHub贡献图表" style="width: 100%;">
5.Telegram频道订阅数API
展示您的Telegram频道订阅人数。
<?php
function getTelegramChannelInfo($channel_name) {
// 需要通过Telegram Bot API获取频道信息
$bot_token = "您的Telegram机器人令牌";
$url = "https://api.telegram.org/bot".$bot_token."/getChatMembersCount?chat_id=@".$channel_name;
$data = json_decode(file_get_contents($url), true);
return $data['result'];
}
$channel = "您的频道名称(不含@)";
$subscribers = getTelegramChannelInfo($channel);
echo "@".$channel." 订阅人数: ".$subscribers;
?>
6.王者荣耀战绩API
展示您的王者荣耀游戏数据。
<?php
function getKingGloryStats($openId) {
// 需要通过官方申请接口权限,这里仅提供示例
$apiKey = '你的API密钥';
$url = "https://api.wgapi.com/v2/player?openid={$openId}&token={$apiKey}";
$data = json_decode(file_get_contents($url), true);
if ($data['code'] == 200) {
return [
'nickname' => $data['data']['nickname'],
'tier' => $data['data']['tier_name'],
'win_rate' => $data['data']['win_rate'],
'total_matches' => $data['data']['total_matches']
];
} else {
return null;
}
}
$openId = '您的王者荣耀OpenID';
$stats = getKingGloryStats($openId);
if ($stats) {
echo '<div class="kg-stats">';
echo '<h3>我的王者荣耀战绩</h3>';
echo '<p>昵称: '.$stats['nickname'].'</p>';
echo '<p>段位: '.$stats['tier'].'</p>';
echo '<p>胜率: '.$stats['win_rate'].'%</p>';
echo '<p>总场次: '.$stats['total_matches'].'</p>';
echo '</div>';
} else {
echo '数据获取失败';
}
?>
7.Steam游戏状态API
展示您的Steam游戏状态和最近玩的游戏。
<?php
function getSteamGameStatus($steamid, $apikey) {
$url = "https://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v1/?key=".$apikey."&steamid=".$steamid."&format=json";
$data = json_decode(file_get_contents($url), true);
return $data['response']['games'];
}
$steamid = '你的SteamID';
$apikey = '你的Steam API密钥';
$games = getSteamGameStatus($steamid, $apikey);
echo "<h3>我最近玩的游戏</h3>";
foreach(array_slice($games, 0, 3) as $game) {
echo $game['name']." - 最近游戏时间: ".round($game['playtime_2weeks']/60, 1)." 小时<br>";
}
?>
8. 微博热搜 API
显示实时热搜榜单,访客不用跳转到微博也能看热点:
function getWeiboHotSearch() {
$url = "https://weibo.com/ajax/side/hotSearch";
$context = stream_context_create([
'http' => [
'header' => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
]
]);
$data = json_decode(file_get_contents($url, false, $context), true);
return $data['data']['realtime'];
}
echo "<h3>微博热搜</h3>";
echo "<ul>";
foreach(array_slice(getWeiboHotSearch(), 0, 10) as $item) {
echo "<li>".$item['note']." <small>(".number_format($item['num']).")</small></li>";
}
echo "</ul>";
9. 抖音热门话题 API
显示当前抖音热词和热度值,贴近流行趋势:
function getDouyinHotTopics() {
// 使用公开的抖音热榜API
$url = "https://www.iesdouyin.com/web/api/v2/hotsearch/billboard/word/";
$context = stream_context_create([
'http' => [
'header' => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
]
]);
$data = json_decode(file_get_contents($url, false, $context), true);
if (isset($data['word_list'])) {
return $data['word_list'];
} else {
return [];
}
}
$topics = getDouyinHotTopics();
echo '<h3>抖音热门话题</h3>';
echo '<ul class="douyin-topics">';
foreach (array_slice($topics, 0, 10) as $index => $topic) {
echo '<li>';
echo '<span class="rank">'.($index + 1).'</span> ';
echo $topic['word'];
if (isset($topic['hot_value'])) {
echo ' <small>('.number_format($topic['hot_value']).')</small>';
}
echo '</li>';
}
echo '</ul>';
10.百度热搜榜API
展示百度搜索热榜内容。
<?php
function getBaiduHotSearch() {
$url = "https://top.baidu.com/api/board?platform=wise&tab=realtime";
$context = stream_context_create([
'http' => [
'header' => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
]
]);
$data = json_decode(file_get_contents($url, false, $context), true);
if (isset($data['data']['cards'][0]['content'])) {
return $data['data']['cards'][0]['content'];
} else {
return [];
}
}
$hotSearches = getBaiduHotSearch();
echo '<h3>百度热搜榜</h3>';
echo '<ul class="baidu-hot">';
foreach (array_slice($hotSearches, 0, 10) as $index => $item) {
echo '<li>';
echo '<span class="rank">'.($index + 1).'</span> ';
echo $item['word'];
if (isset($item['hotScore'])) {
echo ' <small>('.number_format($item['hotScore']).')</small>';
}
echo '</li>';
}
echo '</ul>';
?>
11.哔哩哔哩热搜API
展示B站当前热搜词。
<?php
function getBilibiliHotSearch() {
$url = "https://api.bilibili.com/x/web-interface/search/square?limit=10";
$context = stream_context_create([
'http' => [
'header' => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
]
]);
$data = json_decode(file_get_contents($url, false, $context), true);
if (isset($data['data']['trending']['list'])) {
return $data['data']['trending']['list'];
} else {
return [];
}
}
$hotSearch = getBilibiliHotSearch();
echo '<h3>B站热搜</h3>';
echo '<ul class="bilibili-hot">';
foreach ($hotSearch as $index => $item) {
echo '<li>';
echo '<span class="rank">'.($index + 1).'</span> ';
echo $item['keyword'];
if (isset($item['show_name'])) {
echo ' <small>'.$item['show_name'].'</small>';
}
echo '</li>';
}
echo '</ul>';
?>
12.天气API
根据IP或设定位置显示天气信息。
<?php
function getWeather($city) {
$url = "http://wthrcdn.etouch.cn/weather_mini?city=".urlencode($city);
$data = json_decode(file_get_contents($url), true);
return $data['data']['forecast'][0];
}
$city = '北京';
$weather = getWeather($city);
echo $city.' 今天: '.$weather['type'].', '.$weather['low'].' ~ '.$weather['high'];
?>
13.每日诗词API
展示随机古诗词。
<?php
$poetry = json_decode(file_get_contents('https://v2.jinrishici.com/one.json'), true);
echo $poetry['data']['content'].'<br>—— '.$poetry['data']['origin']['dynasty'].' · '.$poetry['data']['origin']['author'].'《'.$poetry['data']['origin']['title'].'》';
?>
14.随机猫咪图片API
每次刷新页面展示不同的猫咪图片。
<img src="https://cataas.com/cat" alt="Random Cat" style="max-width:100%;">
15.随机狗狗图片API
展示随机狗狗图片。
<?php
$dog = json_decode(file_get_contents('https://dog.ceo/api/breeds/image/random'), true);
echo '<img src="'.$dog['message'].'" alt="Random Dog" style="max-width:100%;">';
?>
16.实时汇率转换API
展示不同货币之间的实时汇率。
<?php
function getExchangeRate($from, $to) {
$url = "https://api.exchangerate-api.com/v4/latest/".$from;
$data = json_decode(file_get_contents($url), true);
return $data['rates'][$to];
}
echo "1 USD = ".getExchangeRate('USD', 'CNY')." CNY";
?>
17.历史上的今天API
展示历史上的今天发生的事件。
<?php
$date = date('m/d');
$url = "https://baike.baidu.com/cms/home/eventsOnHistory/".$date.".json";
$data = json_decode(file_get_contents($url), true);
$events = $data[$date];
echo "<h3>历史上的今天(".$date.")</h3>";
foreach(array_slice($events, 0, 5) as $event) {
echo $event['year']."年: ".$event['title']."<br>";
}
?>
19.每日NASA图片API
展示NASA每日天文图片。
<?php
$nasa = json_decode(file_get_contents('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY'), true);
echo '<h3>'.$nasa['title'].'</h3>';
echo '<img src="'.$nasa['url'].'" alt="'.$nasa['title'].'" style="max-width:100%;">';
echo '<p>'.$nasa['explanation'].'</p>';
?>
20.代码高亮API
使用Prism或Highlight.js自动为代码块添加语法高亮。
<!-- 在header.php中添加 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/themes/prism.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/prism.min.js"></script>
21.IP地理位置显示API
展示访客的地理位置。
<?php
function getIpLocation($ip) {
$url = "http://ip-api.com/json/".$ip."?lang=zh-CN";
$data = json_decode(file_get_contents($url), true);
return $data['country'].' '.$data['city'];
}
$ip = $_SERVER['REMOTE_ADDR'];
echo "您来自: ".getIpLocation($ip);
?>
22.实时在线人数统计API
展示当前在线访问人数。
<?php
// 需要在数据库中创建相关表来记录访问信息
function getOnlineCount() {
// 过期时间设置为15分钟
$expire = 15 * 60;
$now = time();
// 清理过期会话
$db = Typecho_Db::get();
$db->query($db->delete('table.online')
->where('time < ?', $now - $expire));
// 更新当前会话
$sid = session_id();
if($sid) {
$exist = $db->fetchRow($db->select('sid')->from('table.online')
->where('sid = ?', $sid));
if($exist) {
$db->query($db->update('table.online')
->rows(array('time' => $now))
->where('sid = ?', $sid));
} else {
$db->query($db->insert('table.online')
->rows(array('sid' => $sid, 'time' => $now)));
}
}
// 获取在线人数
$online = $db->fetchObject($db->select('COUNT(*) AS count')->from('table.online'))->count;
return $online;
}
echo "当前在线: ".getOnlineCount()." 人";
?>
23.随机二次元图片API
展示随机的二次元图片。
<?php
echo '<img src="https://api.ixiaowai.cn/api/api.php" alt="Random Anime Image" style="max-width:100%;">';
?>
24.代码运行结果展示API
展示代码片段的实际运行结果。
<?php
function executeCodeSnippet($code, $language) {
$result = '';
switch($language) {
case 'php':
ob_start();
eval($code);
$result = ob_get_clean();
break;
case 'js':
// 需要服务器支持Node.js或使用在线执行服务
// 此处使用前端JavaScript执行
$result = '<div id="js-result"></div>
<script>
try {
const result = eval(`'.$code.'`);
document.getElementById("js-result").innerText = result;
} catch(e) {
document.getElementById("js-result").innerText = "Error: " + e.message;
}
</script>';
break;
case 'python':
// 需要服务器支持Python
$tempFile = tempnam(sys_get_temp_dir(), 'py_');
file_put_contents($tempFile, $code);
$result = shell_exec('python '.$tempFile);
unlink($tempFile);
break;
}
return $result;
}
$code = 'echo "Hello, World!";';
$result = executeCodeSnippet($code, 'php');
echo "<h3>代码运行结果</h3>";
echo "<pre>".$result."</pre>";
?>
25.二维码生成API
为文章或链接生成二维码。
<?php
function generateQRCode($text, $size = 150) {
$url = "https://api.qrserver.com/v1/create-qr-code/?size=".$size."x".$size."&data=".urlencode($text);
return $url;
}
// 生成当前文章的二维码
$current_url = Typecho_Common::url($this->permalink);
$qrcode_url = generateQRCode($current_url);
echo "<h3>扫描分享文章</h3>";
echo '<img src="'.$qrcode_url.'" alt="QR Code">';
?>
26.访客地图API
展示访客来源地理位置的世界地图。
<?php
// 首先需要收集访客IP并存储地理位置信息
function logVisitorLocation() {
$ip = $_SERVER['REMOTE_ADDR'];
$data = json_decode(file_get_contents("http://ip-api.com/json/".$ip."?fields=country,lat,lon"), true);
if($data && isset($data['country'])) {
$db = Typecho_Db::get();
$db->query($db->insert('table.visitors')
->rows(array(
'ip' => $ip,
'country' => $data['country'],
'latitude' => $data['lat'],
'longitude' => $data['lon'],
'time' => time()
)));
}
}
// 显示访客地图
function displayVisitorMap() {
$db = Typecho_Db::get();
$visitors = $db->fetchAll($db->select('country', 'latitude', 'longitude', 'COUNT(*) as count')
->from('table.visitors')
->group('country'));
$markers = array();
foreach($visitors as $visitor) {
$markers[] = array(
'lat' => $visitor['latitude'],
'lng' => $visitor['longitude'],
'title' => $visitor['country'].' ('.$visitor['count'].')'
);
}
$markers_json = json_encode($markers);
return '
<div id="visitor-map" style="width:100%;height:300px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById("visitor-map"), {
zoom: 2,
center: {lat: 30, lng: 0}
});
var markers = '.$markers_json.';
markers.forEach(function(marker) {
new google.maps.Marker({
position: {lat: parseFloat(marker.lat), lng: parseFloat(marker.lng)},
map: map,
title: marker.title
});
});
}
google.maps.event.addDomListener(window, "load", initMap);
</script>';
}
// 记录当前访客
logVisitorLocation();
// 显示地图
echo "<h3>访客地图</h3>";
echo displayVisitorMap();
?>
27.随机表情包API
随机展示一个表情包图片。
<?php
function getRandomMeme() {
// 表情包图片URL数组
$memes = array(
"https://i.imgur.com/1NPi2kN.jpg",
"https://i.imgur.com/GXPO2Yh.jpg",
"https://i.imgur.com/C5YRB0x.jpg",
"https://i.imgur.com/tZNOabj.jpg",
"https://i.imgur.com/wJLRN9A.jpg"
);
return $memes[array_rand($memes)];
}
echo "<h3>随机表情包</h3>";
echo '<img src="'.getRandomMeme().'" style="max-width:300px;" alt="Random Meme">';
?>
28.随机美食食谱API
展示随机美食食谱。
<?php
function getRandomRecipe() {
$url = "https://www.themealdb.com/api/json/v1/1/random.php";
$data = json_decode(file_get_contents($url), true);
return $data['meals'][0];
}
$recipe = getRandomRecipe();
echo "<h3>今日美食推荐: ".$recipe['strMeal']."</h3>";
echo '<img src="'.$recipe['strMealThumb'].'" style="max-width:300px;">';
echo "<h4>材料:</h4><ul>";
for($i=1; $i<=20; $i++) {
if(!empty($recipe['strIngredient'.$i])) {
echo "<li>".$recipe['strIngredient'.$i]." - ".$recipe['strMeasure'.$i]."</li>";
}
}
echo "</ul>";
?>
29.倒计时日期提醒API
展示距离特定日期的倒计时。
<?php
function getDaysUntil($date, $event_name) {
$now = time();
$event_time = strtotime($date);
$days_left = ceil(($event_time - $now) / 86400);
return array(
'name' => $event_name,
'date' => $date,
'days' => $days_left
);
}
$events = array(
getDaysUntil('2023-12-25', '圣诞节'),
getDaysUntil('2024-01-01', '元旦'),
getDaysUntil('2024-02-10', '春节'), // 根据实际日期调整
);
echo "<h3>节日倒计时</h3>";
echo "<ul>";
foreach($events as $event) {
if($event['days'] > 0) {
echo "<li>距离 ".$event['name']." 还有 ".$event['days']." 天</li>";
} else if($event['days'] == 0) {
echo "<li>今天是 ".$event['name']."!</li>";
}
}
echo "</ul>";
?>
30.Minecraft服务器状态API
显示您的Minecraft服务器状态。
<?php
function getMinecraftServerStatus($server) {
$url = "https://api.mcsrvstat.us/2/".$server;
$data = json_decode(file_get_contents($url), true);
return $data;
}
$server = 'mc.hypixel.net'; // 服务器地址
$status = getMinecraftServerStatus($server);
echo "<h3>Minecraft服务器状态</h3>";
echo "服务器: ".$server."<br>";
echo "状态: ".($status['online'] ? '在线' : '离线')."<br>";
if($status['online']) {
echo "当前玩家: ".$status['players']['online']."/".$status['players']['max']."<br>";
echo "版本: ".$status['version']."<br>";
}
?>
三、集成到 Typecho
拿到代码后,怎么加到 Typecho 博客里?
1. 直接修改主题文件
如果想让 API 数据固定显示在某个位置(比如侧边栏、底部),直接修改主题模板文件:
- 显示在侧边栏:找到主题文件夹里的
sidebar.php
,在合适位置粘贴代码(比如 “个人信息” 模块下面); - 显示在底部:修改
footer.php
,粘贴代码到版权信息上方; - 注意:修改前备份原文件,避免出错后无法恢复。
2. 创建独立页面
如果想做一个 “热点汇总页”,专门展示微博 / 抖音热搜,可创建独立页面:
- 登录 Typecho 后台,点击 “管理→独立页面→新建页面”;
- 标题填 “实时热点”,内容编辑器切换到 “HTML 模式”,粘贴热搜 API 代码;
- 选择合适的页面模板(比如 “空白模板”),保存后访问页面,就能看到实时热点。
3. 封装成插件
如果想随时启用 / 禁用 API 功能,可封装成 Typecho 插件:
- 在 Typecho 的
usr/plugins/
目录下新建文件夹(比如ApiIntegration
); - 新建
Plugin.php
文件,将 API 函数和调用代码按 Typecho 插件格式封装(可参考官方插件示例); - 后台 “插件管理” 中启用插件,就能在对应位置显示 API 数据,不想用时直接禁用即可。
4. 用 Widget 调用
如果想在不同位置灵活调用 API 数据,可创建自定义 Widget:
- 在主题的
Widget/
目录下新建ApiWidget.php
,编写 Widget 类,包含 API 调用逻辑; - 在模板文件中用
<?php $this->widget('Widget_ApiWidget')->render(); ?>
调用,想显示在哪就插在哪。
四、必看注意事项:避免 API 调用出问题
用 API 时,这 4 个细节要注意,不然可能导致数据获取失败或博客加载变慢:
1. 确认服务器支持 file_get_contents
这些 API 代码都用了file_get_contents
函数,需要服务器开启allow_url_fopen
功能:
- 怎么查:新建一个
phpinfo.php
文件,内容写<?php phpinfo(); ?>
,上传到服务器访问,搜索 “allow_url_fopen”,显示 “On” 就是开启状态; - 若未开启:联系服务器服务商帮忙开启,或用
curl
函数替换。
2. 部分 API 需 API 密钥
有些 API(比如某些天气 API),可能需要先在官方平台注册,拿到密钥再填到代码里,按官方文档操作即可。
3. 加缓存,减少请求次数
频繁调用 API 会增加服务器压力,还可能因 “请求过多” 被 API 平台封禁,建议加缓存:
- 简单方法:用 Typecho 自带的缓存功能,或在 API 函数中添加 “缓存时间”,比如获取一次热搜后,30 分钟内不再重新请求,直接用缓存数据。
4. 遵守 API 使用限制
每个 API 平台都有使用规则(比如每秒最大请求数),不要过度调用:
- 建议:个人博客用这些 API,每天请求次数控制在平台规定的合理范围内,避免被判定为 “恶意请求” 导致封禁。
五、总结
通过这些 API,你可以为Typecho博客增添更多动态和个性化元素,提升用户体验和互动性,让你的 Typecho 博客从 “静态文字” 变成一个可以“动态互动” 的小空间!
