WordPress 通过 FreshRSS 实现友圈rss订阅功能

网站APP 4 个月前 回复

, , ,

1、首先,需要搭建部署FreshRSS,此处搭建部署过程就省略了,网上搜就有,数据库选择mysql可能会报错,原因不清楚,但是选择SQLite就没问题
2、搭建好之后,登陆进去之后【设置->管理->认证】去开启允许api

3、进入【设置->账户->账户管理->API 管理】设置密码并提交保存,记住设置的api密码

4、 在自己站点根目录下创建一个php文件,用于放FreshRSS api调用函数,例如:rss.php

<?php
/**
 * 获取最新订阅文章并生成JSON文件
 */
function getAllSubscribedArticlesAndSaveToJson($user, $password)
{
    $apiUrl = 'https://你部署FreshRSS的域名/api/greader.php';
    $loginUrl = $apiUrl . '/accounts/ClientLogin?Email=' . urlencode($user) . '&Passwd=' . urlencode($password);
    $loginResponse = curlRequest($loginUrl);
    if (strpos($loginResponse, 'Auth=') !== false) {
        $authToken = substr($loginResponse, strpos($loginResponse, 'Auth=') + 5);
        $articlesUrl = $apiUrl . '/reader/api/0/stream/contents/reading-list?&n=1000';
        $articlesResponse = curlRequest($articlesUrl, $authToken);
        $articles = json_decode($articlesResponse, true);
        if (isset($articles['items'])) {
            usort($articles['items'], function ($a, $b) {
                return $b['published'] - $a['published'];
            });
            $subscriptionsUrl = $apiUrl . '/reader/api/0/subscription/list?output=json';
            $subscriptionsResponse = curlRequest($subscriptionsUrl, $authToken);
            $subscriptions = json_decode($subscriptionsResponse, true);
            if (isset($subscriptions['subscriptions'])) {
                $subscriptionMap = array();
                foreach ($subscriptions['subscriptions'] as $subscription) {
                    $subscriptionMap[$subscription['id']] = $subscription;
                }
                $formattedArticles = array();
                foreach ($articles['items'] as $article) {
                    $desc_length = mb_strlen(strip_tags(html_entity_decode($article['summary']['content'], ENT_QUOTES, 'UTF-8')), 'UTF-8');
                    if ($desc_length > 20) {
                        $short_desc = mb_substr(strip_tags(html_entity_decode($article['summary']['content'], ENT_QUOTES, 'UTF-8')), 0, 99, 'UTF-8') . '...';
                    } else {
                        $short_desc = strip_tags(html_entity_decode($article['summary']['content'], ENT_QUOTES, 'UTF-8'));
                    }
                    
                    $formattedArticle = array(
                        'site_name' => $article['origin']['title'],
                        'title' => $article['title'],
                        'link' => $article['alternate'][0]['href'],
                        'time' => date('Y-m-d H:i', $article['published']),
                        'description' => $short_desc,
                    );

                    $subscriptionId = $article['origin']['streamId'];
                    if (isset($subscriptionMap[$subscriptionId])) {
                        $subscription = $subscriptionMap[$subscriptionId];
                        $iconUrl = $subscription['iconUrl'];
                        $filename = 'https://你部署FreshRSS的域名/'.substr($iconUrl, strrpos($iconUrl, '/') + 1);
                        $formattedArticle['icon'] = $filename;
                    }

                    $formattedArticles[] = $formattedArticle;
                }

                saveToJsonFile($formattedArticles);
                return $formattedArticles;
            } else {
                echo 'Error retrieving articles.';
            }
        } else {
            echo 'Error retrieving articles.';
        }
    } else {
        echo 'Login failed.';
    }
    return null;
}
function curlRequest($url, $authToken = null)
{
    $ch = curl_init($url);
    if ($authToken) {
        $headers = array(
            'Authorization: GoogleLogin auth=' . $authToken,
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}
/**
 * 将数据保存到JSON文件中
 */
function saveToJsonFile($data)
{
    $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    file_put_contents('output.json', $json);
    echo '数据已保存到JSON文件中';
}

// 调用函数并提供用户名和密码
getAllSubscribedArticlesAndSaveToJson('这里是FreshRSS的用户名', '这里是第3步设置的api密码');

5、在主题中调用,在需要显示订阅数据的地方插入以下代码,样式结构自行调整

<?php
            // 获取JSON数据
            $jsonData = file_get_contents('./output.json');
            // 将JSON数据解析为PHP数组
            $articles = json_decode($jsonData, true);
            // 对文章按时间排序(最新的排在前面)
            usort($articles, function ($a, $b) {
                return strtotime($b['time']) - strtotime($a['time']);
            });
            // 设置每页显示的文章数量
            $itemsPerPage = 30;
            // 生成文章列表
            foreach (array_slice($articles, 0, $itemsPerPage) as $article) {
                $articles_list ='
                图标:' . htmlspecialchars($article['icon']) . '
                站点标题:' . htmlspecialchars($article['site_name']) . '
                文章标题:' . htmlspecialchars($article['title']) . '
                文章内容摘要:' . htmlspecialchars($article['description']) . '
                文章链接:' . htmlspecialchars($article['link']) . '
                文章发布时间:' . htmlspecialchars($article['time']) . '
                ';
                echo $articles_list;
            }
        ?>

6、在宝塔添加一个计划任务,定时访问执行第4步创建的php文件,以更新订阅数据

7、最后就是去你部署好的FreshRSS管理站点添加管理你想要订阅的站点了,访问第4步创建的php文件更新数据

End...

这个方法缺点就是管理有些不太方便,看了下其实FreshRSS api还支持添加和删除订阅,有能力的佬哥可以折腾折腾,可以在自个博客添加个直接添加订阅或者删除的按钮~

原文:https://www.rz.sb/archives/228/

支付宝打赏微信打赏

如果此文对你有帮助,欢迎打赏作者。

发表评论

欢迎回来 (打开)

(必填)