AI摘要

本文介绍了60个有趣且实用的API,它们可以集成到Typecho博客中,让博客更加生动有趣。这些API涵盖了个人社交账号、热搜榜单、工具类、内容增强、博客功能增强以及游戏与娱乐等多个类别。每个API都提供了详细的集成指南和代码示例,方便用户直接应用到自己的博客中。通过这些API的集成,可以为博客添加各种动态和个性化元素,提升用户体验和互动性。同时,文章还提供了集成方法和注意事项,帮助用户更好地利用这些API。

引言

突发奇想,搜集了一些公开API,为博客添加一些动态和个性化的元素让网站更加生动有趣。本文介绍60个有趣的API,它们都可以集成到Typecho博客中,让您的博客脱颖而出。

目录

  1. 个人社交账号API
  2. 热搜榜单API
  3. 工具类API
  4. 内容增强类API
  5. 博客功能增强类API
  6. 游戏与娱乐类API

个人社交账号API

1. QQ等级显示

通过QQ空间API获取您的QQ等级、成长值等信息,并在博客中展示。

<?php
// 在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号';
echo '我的QQ等级: '.getQQLevel($qq);
?>

2. QQ音乐状态API

展示您正在听的QQ音乐歌曲信息。

<?php
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&notice=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号';
$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主数据

展示您的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. 网易云音乐状态

展示您最近听的歌曲或者创建一个迷你播放器。

<?php
// 网易云音乐用户歌单获取
function getNeteaseMusicPlaylist($uid) {
    $url = "http://music.163.com/api/user/playlist/?offset=0&limit=1&uid=".$uid;
    $data = json_decode(file_get_contents($url), true);
    return $data['playlist'][0]['id'];
}

$uid = '你的网易云音乐ID';
$playlistId = getNeteaseMusicPlaylist($uid);
?>

<!-- 添加播放器 -->
<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 
src="//music.163.com/outchain/player?type=2&id=<?php echo $playlistId; ?>&auto=0&height=66"></iframe>

5. GitHub贡献统计

在博客上展示您的GitHub贡献图表。

<img src="https://ghchart.rshah.org/用户名" alt="GitHub贡献图表" style="width: 100%;">

6. 豆瓣读书/电影

展示您最近阅读的书籍或观看的电影。

<?php
function getDoubanRecentBooks($uid) {
    $url = "https://api.douban.com/v2/book/user/".$uid."/collections?status=reading&count=5";
    $data = json_decode(file_get_contents($url), true);
    return $data;
}

$uid = '你的豆瓣ID';
$books = getDoubanRecentBooks($uid);
foreach ($books['collections'] as $book) {
    echo $book['book']['title'].'<br>';
}
?>

7. Instagram基本数据

通过Instagram API展示您的基本数据。

<?php
function getInstagramBasicData($access_token) {
    $url = "https://graph.instagram.com/me?fields=id,username,account_type&access_token=".$access_token;
    $data = json_decode(file_get_contents($url), true);
    return $data;
}

$access_token = "您的Instagram访问令牌";
$data = getInstagramBasicData($access_token);
echo "Instagram用户名: ".$data['username'];
?>

8. Discord服务器状态

展示您的Discord服务器状态和成员数。

<?php
function getDiscordServerInfo($server_id, $bot_token) {
    $url = "https://discord.com/api/guilds/".$server_id;
    $context = stream_context_create([
        'http' => [
            'header' => 'Authorization: Bot '.$bot_token
        ]
    ]);
    $data = json_decode(file_get_contents($url, false, $context), true);
    return $data;
}

$server_id = "您的Discord服务器ID";
$bot_token = "您的Discord机器人令牌";
$server = getDiscordServerInfo($server_id, $bot_token);
echo "Discord服务器: ".$server['name']."<br>";
echo "成员数: ".$server['approximate_member_count'];
?>

9. Telegram频道订阅数

展示您的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;
?>

10. 小红书笔记展示

在博客中展示您最近的小红书笔记。

<?php
function getXiaoHongShuPosts($userId) {
    // 获取小红书用户公开信息
    $url = "https://www.xiaohongshu.com/user/profile/" . $userId;
    $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'
        ]
    ]);
    $html = file_get_contents($url, false, $context);
    
    // 使用正则表达式提取笔记信息
    // 注意:这是一个简化版,实际需要考虑网站结构变化
    preg_match_all('/<div class="note-item">(.*?)<\/div>/s', $html, $matches);
    
    $posts = [];
    foreach ($matches[1] as $match) {
        if (preg_match('/<img src="(.*?)"/s', $match, $img) && 
            preg_match('/<div class="title">(.*?)<\/div>/s', $match, $title)) {
            $posts[] = [
                'title' => trim($title[1]),
                'image' => $img[1]
            ];
        }
    }
    
    return $posts;
}

$userId = '你的小红书ID';
$posts = getXiaoHongShuPosts($userId);

echo '<h3>我的小红书笔记</h3>';
echo '<div class="xhs-container" style="display:flex;flex-wrap:wrap;">';
foreach (array_slice($posts, 0, 4) as $post) {
    echo '<div style="width:48%;margin:1%;box-sizing:border-box;">';
    echo '<img src="'.$post['image'].'" style="width:100%;border-radius:8px;" />';
    echo '<p style="margin:5px 0;font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">'.$post['title'].'</p>';
    echo '</div>';
}
echo '</div>';
?>

11. 王者荣耀战绩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 '数据获取失败';
}
?>

12. Steam游戏状态

展示您的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>";
}
?>

热搜榜单API

13. 微博热搜API

展示实时的微博热搜榜单。

<?php
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>";
?>

14. 知乎热榜API

展示知乎热门话题。

<?php
function getZhihuHotTopics() {
    $url = "https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total?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);
    return $data['data'];
}

echo "<h3>知乎热榜</h3>";
echo "<ul>";
foreach(getZhihuHotTopics() as $item) {
    echo "<li><a href='https://www.zhihu.com/question/".$item['target']['id']."' target='_blank'>".$item['target']['title']."</a></li>";
}
echo "</ul>";
?>

15. 抖音热门话题

展示当前抖音热门话题和标签。

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

16. 百度热搜榜

展示百度搜索热榜内容。

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

17. 腾讯新闻热点

展示腾讯新闻热点话题。

<?php
function getTencentHotNews() {
    $url = "https://i.news.qq.com/trpc.qqnews_web.kv_srv.kv_srv_http_proxy/list?sub_srv_id=24hours&srv_id=pc";
    $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']['list'])) {
        return $data['data']['list'];
    } else {
        return [];
    }
}

$hotNews = getTencentHotNews();
echo '<h3>腾讯新闻热点</h3>';
echo '<ul class="tencent-hot">';
foreach (array_slice($hotNews, 0, 10) as $index => $news) {
    echo '<li>';
    echo '<span class="rank">'.($index + 1).'</span> ';
    echo '<a href="'.$news['url'].'" target="_blank">'.$news['title'].'</a>';
    echo '</li>';
}
echo '</ul>';
?>

18. 哔哩哔哩热搜

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

19. 即刻社区热门

展示即刻社区的热门话题。

<?php
function getJikeCommunityHot() {
    // 即刻热门话题API
    $url = "https://api.ruguoapp.com/1.0/topics/recommendation/list";
    $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'
        ]
    ]);
    
    try {
        $data = json_decode(file_get_contents($url, false, $context), true);
        if (isset($data['data'])) {
            return $data['data'];
        }
    } catch (Exception $e) {
        // 接口可能不稳定,返回一些示例数据
        return [
            ['content' => '今天又是元气满满的一天', 'likeCount' => 2453],
            ['content' => '来分享你的摄影作品', 'likeCount' => 1892],
            ['content' => '程序员日常', 'likeCount' => 1654],
            ['content' => '美食分享计划', 'likeCount' => 1245],
            ['content' => '今日份猫猫', 'likeCount' => 985]
        ];
    }
    
    return [];
}

$topics = getJikeCommunityHot();
echo '<h3>即刻热门话题</h3>';
echo '<ul class="jike-topics">';
foreach (array_slice($topics, 0, 5) as $topic) {
    echo '<li>';
    echo $topic['content'];
    if (isset($topic['likeCount'])) {
        echo ' <small>('.$topic['likeCount'].'人关注)</small>';
    }
    echo '</li>';
}
echo '</ul>';
?>

20. 搜狗热搜榜

展示搜狗搜索引擎热搜榜。

<?php
function getSogouHotSearch() {
    $url = "https://top.sogou.com/hot/json";
    $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'
        ]
    ]);
    
    try {
        $data = json_decode(file_get_contents($url, false, $context), true);
        if (isset($data['data'])) {
            return $data['data'];
        }
    } catch (Exception $e) {
        // 返回示例数据
        return [
            ['keyword' => '热门电影', 'heat' => 9876],
            ['keyword' => '国内新闻头条', 'heat' => 8765],
            ['keyword' => '今日天气', 'heat' => 7654],
            ['keyword' => '最新游戏', 'heat' => 6543],
            ['keyword' => '热门综艺', 'heat' => 5432]
        ];
    }
    
    return [];
}

$hotSearch = getSogouHotSearch();
echo '<h3>搜狗热搜榜</h3>';
echo '<ul class="sogou-hot">';
foreach (array_slice($hotSearch, 0, 10) as $index => $item) {
    echo '<li>';
    echo '<span class="rank">'.($index + 1).'</span> ';
    echo $item['keyword'];
    if (isset($item['heat'])) {
        echo ' <small>('.number_format($item['heat']).')</small>';
    }
    echo '</li>';
}
echo '</ul>';
?>

21. 360热搜榜

展示360搜索热榜内容。

<?php
function get360HotSearch() {
    $url = "https://trends.so.com/hot/search";
    $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'
        ]
    ]);
    
    try {
        $html = file_get_contents($url, false, $context);
        // 使用正则表达式提取数据
        preg_match_all('/<a class="item-title" href="(.*?)" target="_blank">(.*?)<\/a>/s', $html, $matches);
        
        $results = [];
        for ($i = 0; $i < count($matches[2]); $i++) {
            $results[] = [
                'keyword' => trim(strip_tags($matches[2][$i])),
                'url' => $matches[1][$i]
            ];
        }
        
        return $results;
    } catch (Exception $e) {
        // 返回示例数据
        return [
            ['keyword' => '今日头条', 'url' => '#'],
            ['keyword' => '最新电影', 'url' => '#'],
            ['keyword' => '热门游戏', 'url' => '#'],
            ['keyword' => '流行音乐', 'url' => '#'],
            ['keyword' => '科技新闻', 'url' => '#']
        ];
    }
}

$hotSearch = get360HotSearch();
echo '<h3>360热搜榜</h3>';
echo '<ul class="so-hot">';
foreach (array_slice($hotSearch, 0, 10) as $index => $item) {
    echo '<li>';
    echo '<span class="rank">'.($index + 1).'</span> ';
    echo '<a href="'.$item['url'].'" target="_blank">'.$item['keyword'].'</a>';
    echo '</li>';
}
echo '</ul>';
?>

22. 热搜聚合展示

将多个热搜榜单整合到一个页面展示。

<?php
// 获取各平台热搜函数
// ... (使用前面定义的函数) ...

// 展示聚合热搜
echo '<div class="hot-search-container" style="display:flex;flex-wrap:wrap;">';

// 微博热搜
echo '<div class="hot-search-block" style="width:33%;padding:10px;box-sizing:border-box;">';
echo '<h3>微博热搜</h3>';
echo '<ul>';
foreach(array_slice(getWeiboHotSearch(), 0, 5) as $index => $item) {
    echo '<li><span>'.($index + 1).'</span> '.$item['note'].'</li>';
}
echo '</ul>';
echo '</div>';

// 知乎热榜
echo '<div class="hot-search-block" style="width:33%;padding:10px;box-sizing:border-box;">';
echo '<h3>知乎热榜</h3>';
echo '<ul>';
foreach(array_slice(getZhihuHotTopics(), 0, 5) as $index => $item) {
    echo '<li><span>'.($index + 1).'</span> '.$item['target']['title'].'</li>';
}
echo '</ul>';
echo '</div>';

// 百度热搜
echo '<div class="hot-search-block" style="width:33%;padding:10px;box-sizing:border-box;">';
echo '<h3>百度热搜</h3>';
echo '<ul>';
$baiduHot = getBaiduHotSearch();
foreach(array_slice($baiduHot, 0, 5) as $index => $item) {
    echo '<li><span>'.($index + 1).'</span> '.$item['word'].'</li>';
}
echo '</ul>';
echo '</div>';

echo '</div>';
?>

工具类API

23. 天气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'];
?>

24. 一言API

随机展示一句名言。

<?php
$hitokoto = json_decode(file_get_contents('https://v1.hitokoto.cn/'), true);
echo $hitokoto['hitokoto'].' —— '.$hitokoto['from'];
?>

25. 每日诗词

展示随机古诗词。

<?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'].'》';
?>

26. 随机猫咪图片

每次刷新页面展示不同的猫咪图片。

<img src="https://cataas.com/cat" alt="Random Cat" style="max-width:100%;">

27. 随机狗狗图片

展示随机狗狗图片。

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

28. 实时汇率转换

展示不同货币之间的实时汇率。

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

29. 历史上的今天

展示历史上的今天发生的事件。

<?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>";
}
?>

30. 每日NASA图片

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

31. 随机笑话

展示随机笑话。

<?php
$joke = json_decode(file_get_contents('https://v2.jokeapi.dev/joke/Any?lang=zh'), true);
if($joke['type'] == 'single') {
    echo $joke['joke'];
} else {
    echo $joke['setup'].'<br>'.$joke['delivery'];
}
?>

32. 实时疫情数据

展示实时的新冠疫情数据。

<?php
$covid = json_decode(file_get_contents('https://lab.isaaclin.cn/nCoV/api/overall'), true);
$data = $covid['results'][0];
echo "确诊: ".$data['confirmedCount']."<br>";
echo "治愈: ".$data['curedCount']."<br>";
echo "死亡: ".$data['deadCount']."<br>";
echo "更新时间: ".date('Y-m-d H:i:s', $data['updateTime']/1000);
?>

博客功能增强类API

33. 代码高亮

使用Prism或Highlight.js自动为代码块添加语法高亮。

<!-- 在header.php中添加 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.23.0/themes/prism.css">
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.23.0/prism.min.js"></script>

34. 文章阅读时间估算

根据文章字数自动计算阅读时间。

<?php
function readingTime($content) {
    $wordCount = mb_strlen(strip_tags($content), 'UTF-8');
    $minutes = ceil($wordCount / 400); // 假设阅读速度为400字/分钟
    return $minutes;
}

// 在文章页面调用
$readTime = readingTime($this->content);
echo "预计阅读时间: ".$readTime." 分钟";
?>

35. IP地理位置显示

显示访客的地理位置。

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

36. 实时在线人数统计

显示当前在线访问人数。

<?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()." 人";
?>

37. 文章热度排行

根据阅读量、评论数等显示热门文章。

<?php
function getHotPosts($limit = 5) {
    $db = Typecho_Db::get();
    $posts = $db->fetchAll($db->select('cid', 'title', 'views')
        ->from('table.contents')
        ->where('type = ?', 'post')
        ->where('status = ?', 'publish')
        ->order('views', Typecho_Db::SORT_DESC)
        ->limit($limit));
    
    return $posts;
}

echo "<h3>热门文章</h3>";
echo "<ul>";
foreach(getHotPosts() as $post) {
    echo '<li><a href="'.Typecho_Router::url('post', array('cid' => $post['cid'])).'">'.$post['title'].'('.$post['views'].'阅读)</a></li>';
}
echo "</ul>";
?>

游戏与娱乐类API

38. 随机二次元图片

展示随机的二次元图片。

<?php
echo '<img src="https://api.ixiaowai.cn/api/api.php" alt="Random Anime Image" style="max-width:100%;">';
?>

39. 每日一句英语

显示每日英语句子及翻译。

<?php
function getDailyEnglish() {
    $url = "https://api.vvhan.com/api/en";
    $data = json_decode(file_get_contents($url), true);
    return $data;
}

$english = getDailyEnglish();
echo "<h3>每日一句</h3>";
echo "<p><i>".$english['data']['en']."</i></p>";
echo "<p>".$english['data']['zh']."</p>";
?>

40. 随机密码生成器

生成随机安全密码。

<?php
function generateRandomPassword($length = 12) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+';
    $password = '';
    for($i = 0; $i < $length; $i++) {
        $password .= $chars[rand(0, strlen($chars) - 1)];
    }
    return $password;
}

echo "<h3>随机安全密码</h3>";
echo "<code>".generateRandomPassword()."</code>";
?>

41. 随机色彩搭配

提供随机的色彩搭配方案。

<?php
function getRandomColorPalette() {
    $palette = array();
    for($i = 0; i < 5; $i++) {
        $color = sprintf('#%06X', mt_rand(0, 0xFFFFFF));
        $palette[] = $color;
    }
    return $palette;
}

$colors = getRandomColorPalette();
echo "<h3>今日色彩搭配</h3>";
echo "<div style='display:flex;'>";
foreach($colors as $color) {
    echo "<div style='width:50px;height:50px;background-color:".$color.";'></div>";
}
echo "</div>";
echo "<div style='display:flex;'>";
foreach($colors as $color) {
    echo "<div style='width:50px;text-align:center;'>".$color."</div>";
}
echo "</div>";
?>

42. 文章相关度推荐

基于内容相似度推荐相关文章。

<?php
function getSimilarPosts($content, $exclude_cid, $limit = 5) {
    // 提取当前文章关键词
    $keywords = preg_split('/\s+/', strip_tags($content));
    $keywords = array_filter($keywords, function($word) {
        return mb_strlen($word, 'UTF-8') > 2; // 过滤短词
    });
    
    // 获取所有其他文章
    $db = Typecho_Db::get();
    $posts = $db->fetchAll($db->select('cid', 'title', 'text')
        ->from('table.contents')
        ->where('type = ?', 'post')
        ->where('status = ?', 'publish')
        ->where('cid <> ?', $exclude_cid));
    
    // 计算相似度
    $scores = array();
    foreach($posts as $post) {
        $post_text = strip_tags($post['text']);
        $score = 0;
        foreach($keywords as $word) {
            $count = substr_count(strtolower($post_text), strtolower($word));
            $score += $count;
        }
        $scores[$post['cid']] = $score;
    }
    
    // 按相似度排序
    arsort($scores);
    
    // 返回前N篇相似度最高的文章
    $result = array();
    $count = 0;
    foreach($scores as $cid => $score) {
        if($score > 0) {
            foreach($posts as $post) {
                if($post['cid'] == $cid) {
                    $result[] = array(
                        'cid' => $cid,
                        'title' => $post['title'],
                        'score' => $score
                    );
                    $count++;
                    break;
                }
            }
            
            if($count >= $limit) break;
        }
    }
    
    return $result;
}

// 在文章页面使用
$similar_posts = getSimilarPosts($this->content, $this->cid);
echo "<h3>相关推荐</h3>";
echo "<ul>";
foreach($similar_posts as $post) {
    echo '<li><a href="'.Typecho_Router::url('post', array('cid' => $post['cid'])).'">'.$post['title'].'</a></li>';
}
echo "</ul>";
?>

博客功能增强类API

43. 代码运行结果展示

展示代码片段的实际运行结果。

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

44. 文本情感分析

分析文章内容的情感倾向。

<?php
function analyzeSentiment($text) {
    // 简单情感分析,实际可使用NLP API
    $positive_words = array('好', '喜欢', '优秀', '精彩', '美丽', '高兴', '开心');
    $negative_words = array('差', '讨厌', '糟糕', '失望', '难过', '伤心', '消极');
    
    $positive_count = 0;
    $negative_count = 0;
    
    foreach($positive_words as $word) {
        $positive_count += substr_count($text, $word);
    }
    
    foreach($negative_words as $word) {
        $negative_count += substr_count($text, $word);
    }
    
    if($positive_count > $negative_count) {
        return array('sentiment' => 'positive', 'score' => $positive_count - $negative_count);
    } else if($negative_count > $positive_count) {
        return array('sentiment' => 'negative', 'score' => $negative_count - $positive_count);
    } else {
        return array('sentiment' => 'neutral', 'score' => 0);
    }
}

// 在文章页面使用
$sentiment = analyzeSentiment($this->content);
echo "文章情感倾向: ";
if($sentiment['sentiment'] == 'positive') {
    echo "<span style='color:green;'>积极 (+".$sentiment['score'].")</span>";
} else if($sentiment['sentiment'] == 'negative') {
    echo "<span style='color:red;'>消极 (-".$sentiment['score'].")</span>";
} else {
    echo "<span style='color:gray;'>中性</span>";
}
?>

45. 二维码生成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">';
?>

46. 文章字数统计

统计博客所有文章的总字数。

<?php
function getTotalWordCount() {
    $db = Typecho_Db::get();
    $posts = $db->fetchAll($db->select('text')
        ->from('table.contents')
        ->where('type = ?', 'post')
        ->where('status = ?', 'publish'));
    
    $total = 0;
    foreach($posts as $post) {
        $total += mb_strlen(strip_tags($post['text']), 'UTF-8');
    }
    
    return $total;
}

$total_words = getTotalWordCount();
echo "博客总字数: ".number_format($total_words)." 字";
?>

47. 访客地图

展示访客来源地理位置的世界地图。

<?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();
?>

48. 随机迷你游戏

在博客中嵌入简单的JS游戏。

<?php
// 随机选择一个迷你游戏
$games = array(
    // 猜数字游戏
    '<div id="guess-game">
        <h3>猜数字游戏</h3>
        <p>我已经想好了一个1-100之间的数字,你猜是多少?</p>
        <input type="number" id="guess-input" min="1" max="100">
        <button id="guess-btn">猜!</button>
        <p id="guess-result"></p>
    </div>
    <script>
        (function() {
            const target = Math.floor(Math.random() * 100) + 1;
            let attempts = 0;
            document.getElementById("guess-btn").addEventListener("click", function() {
                const guess = parseInt(document.getElementById("guess-input").value);
                attempts++;
                if(guess === target) {
                    document.getElementById("guess-result").innerHTML = "恭喜你猜对了!用了" + attempts + "次尝试。";
                } else if(guess < target) {
                    document.getElementById("guess-result").innerHTML = "太小了,再试试!";
                } else {
                    document.getElementById("guess-result").innerHTML = "太大了,再试试!";
                }
            });
        })();
    </script>',
    
    // 石头剪刀布
    '<div id="rps-game">
        <h3>石头剪刀布</h3>
        <div>
            <button id="rock">石头</button>
            <button id="paper">布</button>
            <button id="scissors">剪刀</button>
        </div>
        <p id="rps-result"></p>
        <p>战绩:<span id="rps-score">0胜 0负 0平</span></p>
    </div>
    <script>
        (function() {
            let wins = 0, losses = 0, draws = 0;
            const updateScore = () => {
                document.getElementById("rps-score").textContent = wins + "胜 " + losses + "负 " + draws + "平";
            };
            
            const play = (playerChoice) => {
                const choices = ["rock", "paper", "scissors"];
                const computerChoice = choices[Math.floor(Math.random() * 3)];
                
                let result = "";
                if(playerChoice === computerChoice) {
                    result = "平局!电脑也出了" + (playerChoice === "rock" ? "石头" : playerChoice === "paper" ? "布" : "剪刀");
                    draws++;
                } else if(
                    (playerChoice === "rock" && computerChoice === "scissors") ||
                    (playerChoice === "paper" && computerChoice === "rock") ||
                    (playerChoice === "scissors" && computerChoice === "paper")
                ) {
                    result = "你赢了!电脑出了" + (computerChoice === "rock" ? "石头" : computerChoice === "paper" ? "布" : "剪刀");
                    wins++;
                } else {
                    result = "你输了!电脑出了" + (computerChoice === "rock" ? "石头" : computerChoice === "paper" ? "布" : "剪刀");
                    losses++;
                }
                
                document.getElementById("rps-result").textContent = result;
                updateScore();
            };
            
            document.getElementById("rock").addEventListener("click", () => play("rock"));
            document.getElementById("paper").addEventListener("click", () => play("paper"));
            document.getElementById("scissors").addEventListener("click", () => play("scissors"));
        })();
    </script>'
);

// 随机选择一个游戏
$random_game = $games[array_rand($games)];
echo $random_game;
?>

49. 每日单词学习

每天展示一个英文单词及其解释。

<?php
function getDailyWord() {
    // 使用日期作为种子确保同一天显示相同单词
    $date = date('Ymd');
    srand(intval($date));
    
    $words = array(
        array("word" => "ubiquitous", "part" => "adj.", "meaning" => "存在于无所不在的,普遍存在的"),
        array("word" => "ephemeral", "part" => "adj.", "meaning" => "短暂的,瞬息的"),
        array("word" => "serendipity", "part" => "n.", "meaning" => "意外发现珍奇事物的本领"),
        array("word" => "paradigm", "part" => "n.", "meaning" => "范例,模式"),
        array("word" => "eloquent", "part" => "adj.", "meaning" => "雄辩的,有口才的"),
        array("word" => "pragmatic", "part" => "adj.", "meaning" => "实用的,实际的"),
        array("word" => "resilience", "part" => "n.", "meaning" => "适应力,恢复力"),
        array("word" => "quintessential", "part" => "adj.", "meaning" => "精髓的,典型的"),
        array("word" => "juxtaposition", "part" => "n.", "meaning" => "并置,并列"),
        array("word" => "cacophony", "part" => "n.", "meaning" => "刺耳的声音,不和谐的声音")
    );
    
    $index = rand(0, count($words) - 1);
    return $words[$index];
}

$word = getDailyWord();
echo "<h3>每日单词</h3>";
echo "<p><strong>".$word['word']."</strong> <em>".$word['part']."</em></p>";
echo "<p>".$word['meaning']."</p>";
?>

50. 随机表情包

随机展示一个表情包图片。

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

51. 历史上的今天事件轮播

使用轮播方式展示历史上的今天发生的多个事件。

<?php
function getTodayInHistory() {
    $date = date('m/d');
    $url = "https://baike.baidu.com/cms/home/eventsOnHistory/".$date.".json";
    $data = json_decode(file_get_contents($url), true);
    return $data[$date];
}

$events = getTodayInHistory();
$events = array_slice($events, 0, 10);

echo '<div class="history-carousel">
    <h3>历史上的今天 ('.date('m月d日').')</h3>
    <div class="carousel-container">
        <div id="history-items">';

foreach($events as $index => $event) {
    echo '<div class="history-item '.($index === 0 ? 'active' : '').'">
        <h4>'.$event['year'].'年</h4>
        <p>'.$event['title'].'</p>
    </div>';
}

echo '</div>
        <button id="prev-btn">&lt;</button>
        <button id="next-btn">&gt;</button>
    </div>
</div>

<style>
.history-carousel {
    max-width: 100%;
    margin: 20px 0;
}
.carousel-container {
    position: relative;
    border: 1px solid #eee;
    padding: 15px;
    border-radius: 5px;
    min-height: 120px;
}
.history-item {
    display: none;
}
.history-item.active {
    display: block;
}
#prev-btn, #next-btn {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background: #f0f0f0;
    border: none;
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-radius: 50%;
    cursor: pointer;
}
#prev-btn {
    left: 10px;
}
#next-btn {
    right: 10px;
}
</style>

<script>
document.addEventListener("DOMContentLoaded", function() {
    const items = document.querySelectorAll(".history-item");
    let currentIndex = 0;
    
    document.getElementById("next-btn").addEventListener("click", function() {
        items[currentIndex].classList.remove("active");
        currentIndex = (currentIndex + 1) % items.length;
        items[currentIndex].classList.add("active");
    });
    
    document.getElementById("prev-btn").addEventListener("click", function() {
        items[currentIndex].classList.remove("active");
        currentIndex = (currentIndex - 1 + items.length) % items.length;
        items[currentIndex].classList.add("active");
    });
    
    // 自动轮播
    setInterval(function() {
        document.getElementById("next-btn").click();
    }, 5000);
});
</script>';
?>

52. 热门影视推荐

展示当前热门电影或电视剧。

<?php
function getHotMovies() {
    // 这里可以使用豆瓣API或其他影视API
    // 简单起见,这里使用静态数据
    $movies = array(
        array(
            "title" => "流浪地球2",
            "rating" => "8.3",
            "image" => "https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2885941329.jpg",
            "url" => "https://movie.douban.com/subject/35267208/"
        ),
        array(
            "title" => "满江红",
            "rating" => "7.1",
            "image" => "https://img2.doubanio.com/view/photo/s_ratio_poster/public/p2885955777.jpg",
            "url" => "https://movie.douban.com/subject/35766491/"
        ),
        array(
            "title" => "铃芽之旅",
            "rating" => "7.4",
            "image" => "https://img9.doubanio.com/view/photo/s_ratio_poster/public/p2884182275.jpg",
            "url" => "https://movie.douban.com/subject/35371261/"
        )
    );
    
    return $movies;
}

$movies = getHotMovies();
echo "<h3>热门影视推荐</h3>";
echo "<div style='display:flex;flex-wrap:wrap;'>";
foreach($movies as $movie) {
    echo "<div style='width:33%;padding:10px;box-sizing:border-box;text-align:center;'>";
    echo "<a href='".$movie['url']."' target='_blank'><img src='".$movie['image']."' style='max-width:100%;max-height:150px;'></a>";
    echo "<p>".$movie['title']." (".$movie['rating']."⭐)</p>";
    echo "</div>";
}
echo "</div>";
?>

53. 随机美食食谱

展示随机美食食谱。

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

54. 每日星座运势

根据星座显示每日运势。

<?php
function getHoroscope($sign) {
    $url = "https://api.vvhan.com/api/horoscope?type=".urlencode($sign);
    $data = json_decode(file_get_contents($url), true);
    return $data['data'];
}

$sign = "双鱼座"; // 可以改为任何星座
$horoscope = getHoroscope($sign);
echo "<h3>".$sign."今日运势</h3>";
echo "综合指数: ".$horoscope['index']['all']."<br>";
echo "幸运颜色: ".$horoscope['fortuneColor']."<br>";
echo "幸运数字: ".$horoscope['luckynumber']."<br>";
echo "今日运势: ".$horoscope['fortunetext']."<br>";
?>

55. 每日推荐歌曲

每天随机推荐一首歌曲。

<?php
function getDailyRecommendedSong() {
    // 使用种子确保同一天返回同一首歌
    $date = date('Ymd');
    srand(intval($date));
    
    // 歌曲库(可以扩展)
    $songs = array(
        array("name" => "Shape of You", "artist" => "Ed Sheeran", "id" => "7qiZfU4dY1lWllzX7mPBI3"),
        array("name" => "Dance Monkey", "artist" => "Tones and I", "id" => "1rgnBhdG2JDFTbYkYRZAku"),
        array("name" => "Blinding Lights", "artist" => "The Weeknd", "id" => "0VjIjW4GlUZAMYd2vXMi3b"),
        array("name" => "Someone You Loved", "artist" => "Lewis Capaldi", "id" => "7qEHsqek33rTcFNT9PFqLf"),
        array("name" => "Bad Guy", "artist" => "Billie Eilish", "id" => "2Fxmhks0bxGSBdJ92vM42m")
    );
    
    $index = rand(0, count($songs) - 1);
    return $songs[$index];
}

$song = getDailyRecommendedSong();
echo "<h3>今日推荐歌曲</h3>";
echo $song['name']." - ".$song['artist']."<br>";
echo '<iframe src="https://open.spotify.com/embed/track/'.$song['id'].'" width="300" height="80" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>';
?>

56. 倒计时日期提醒

展示距离特定日期的倒计时。

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

57. 随机壁纸API

每次访问显示不同的精美壁纸。

<?php
echo '<img src="https://api.ixiaowai.cn/gqapi/gqapi.php" style="max-width:100%;" alt="每日壁纸">';
?>

58. Minecraft服务器状态

显示您的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>";
}
?>

59. 随机好看的渐变背景

为您的博客添加随机生成的渐变背景。

<style>
body {
    background: linear-gradient(to right, 
        hsl(<?php echo rand(0, 360); ?>, 100%, 85%), 
        hsl(<?php echo rand(0, 360); ?>, 100%, 85%));
}
</style>

60. 随机英文名言

展示随机英文名言。

<?php
$quote = json_decode(file_get_contents('https://api.quotable.io/random'), true);
echo '"'.$quote['content'].'" — '.$quote['author'];
?>

集成方法

要将这些API集成到Typecho博客中,您可以:

  1. 创建插件:将API功能封装成Typecho插件,这样可以方便地在后台启用/禁用。
  2. 修改主题文件:直接在主题的sidebar.php、footer.php或其他模板文件中添加相关代码。
  3. 创建独立页面:创建一个专门用于展示API数据的独立页面。
  4. 使用Widget:创建自定义Widget并在需要的位置调用。

注意事项

  1. 大多数API调用需要使用PHP的file_get_contents函数,请确保您的服务器已启用allow_url_fopen
  2. 某些API可能需要注册并获取API密钥,请按照相应API的官方文档进行操作。
  3. 考虑使用缓存机制减少API请求次数,提高博客加载速度。
  4. 注意API的使用限制,避免过度调用导致被封禁。

API 汇总列表

个人社交账号API

  1. QQ等级显示API - 展示QQ等级和成长值信息
  2. QQ音乐状态API - 显示正在听的音乐
  3. 哔哩哔哩UP主信息API - 展示粉丝数、视频数、播放量等数据
  4. 网易云音乐状态API - 展示最近听的歌曲或音乐播放器
  5. GitHub贡献统计API - 展示代码贡献图表
  6. 豆瓣读书/电影API - 展示最近阅读的书籍或观看的电影
  7. Instagram基本数据API - 展示Instagram账号基本信息
  8. Discord服务器状态API - 展示服务器状态和成员数
  9. Telegram频道订阅数API - 展示Telegram频道的订阅人数
  10. 小红书笔记展示API - 展示最近的小红书笔记
  11. 王者荣耀战绩API - 展示游戏数据和战绩
  12. Steam游戏状态API - 展示最近玩的游戏和时长

热搜榜单API

  1. 微博热搜API - 展示微博实时热搜榜单
  2. 知乎热榜API - 展示知乎热门话题
  3. 抖音热门话题API - 展示抖音热门话题和标签
  4. 百度热搜榜API - 展示百度搜索热榜内容
  5. 腾讯新闻热点API - 展示腾讯新闻热点话题
  6. 哔哩哔哩热搜API - 展示B站当前热搜词
  7. 即刻社区热门API - 展示即刻社区热门话题
  8. 搜狗热搜榜API - 展示搜狗搜索热榜内容
  9. 360热搜榜API - 展示360搜索热榜内容
  10. 热搜聚合展示API - 整合多平台热搜于一页

工具类API

  1. 天气API - 根据位置显示天气信息
  2. 一言API - 随机展示一句名言
  3. 每日诗词API - 展示随机古诗词
  4. 随机猫咪图片API - 每次刷新显示不同猫咪图片
  5. 随机狗狗图片API - 展示随机狗狗图片
  6. 实时汇率转换API - 展示不同货币之间的实时汇率
  7. 历史上的今天API - 展示历史上的今天发生的事件
  8. 每日NASA图片API - 展示NASA每日天文图片
  9. 随机笑话API - 展示随机笑话
  10. 实时疫情数据API - 展示实时的新冠疫情数据

博客功能增强API

  1. 代码高亮API - 为代码块添加语法高亮
  2. 文章阅读时间估算API - 根据字数计算阅读时间
  3. IP地理位置显示API - 显示访客的地理位置
  4. 实时在线人数统计API - 显示当前在线访问人数
  5. 文章热度排行API - 显示热门文章
  6. 随机二次元图片API - 展示随机的二次元图片
  7. 每日一句英语API - 显示每日英语句子及翻译
  8. 随机密码生成器API - 生成随机安全密码
  9. 随机色彩搭配API - 提供随机的色彩搭配方案
  10. 文章相关度推荐API - 推荐相关文章
  11. 代码运行结果展示API - 展示代码片段的实际运行结果
  12. 文本情感分析API - 分析文章内容的情感倾向
  13. 二维码生成API - 为文章或链接生成二维码
  14. 文章字数统计API - 统计博客所有文章的总字数
  15. 访客地图API - 展示访客来源地理位置的世界地图

游戏与娱乐类API

  1. 随机迷你游戏API - 在博客中嵌入简单的JS游戏
  2. 每日单词学习API - 每天展示一个英文单词及其解释
  3. 随机表情包API - 随机展示一个表情包图片
  4. 历史上的今天事件轮播API - 轮播展示历史上的今天事件
  5. 热门影视推荐API - 展示当前热门电影或电视剧
  6. 随机美食食谱API - 展示随机美食食谱
  7. 每日星座运势API - 根据星座显示每日运势
  8. 每日推荐歌曲API - 每天随机推荐一首歌曲
  9. 倒计时日期提醒API - 展示距离特定日期的倒计时
  10. 随机壁纸API - 每次访问显示不同的精美壁纸
  11. Minecraft服务器状态API - 显示Minecraft服务器状态
  12. 随机好看的渐变背景API - 为博客添加随机生成的渐变背景
  13. 随机英文名言API - 展示随机英文名言

结语

通过集成这些丰富多样的API,你可以为Typecho博客增添更多动态和个性化元素,提升用户体验和互动性。选择适合的博客主题和风格的API进行集成,让你的博客更加与众不同!

记住,合理使用API缓存机制可以有效减少服务器压力和提高页面加载速度。希望本文介绍的这60个API能为您的博客增添更多精彩内容!

有什么问题可在评论区留言,觉得有趣也可以留言!

如果觉得我的文章对你有用,请随意赞赏
END
本文作者:
文章标题:分享60个有趣实用的API及其Typecho博客集成指南
本文地址:https://blog.ybyq.wang/archives/748.html
版权说明:若无注明,本文皆Xuan's blog原创,转载请保留文章出处。