新闻自动采集并通过API发布到博客

  1. 新闻采集 :使用PHP的file_get_contentscURL从RSS源或网页抓取新闻内容。
  2. 页面独立存储:将采集的新闻保存为独立的HTML或Markdown文件。
  3. emlog API集成:通过emlog的API(假设使用emlog的RESTful API)发布文章。
  4. 前端展示:使用HTML5、CSS和JavaScript实现简单的管理界面。

实现代码

以下是一个完整的实现,包括采集、存储和发布功能。假设您有emlog博客的API密钥和URL。

php 复制代码
<?php
// 配置信息
$emlog_api_url = 'http://your-emlog-site.com/api/post'; // 替换为您的emlog API地址
$emlog_api_key = 'your_api_key'; // 替换为您的emlog API密钥
$rss_url = 'https://example.com/rss'; // 替换为目标新闻RSS源
$storage_path = __DIR__ . '/news/'; // 新闻存储目录

// 确保存储目录存在
if (!is_dir($storage_path)) {
    mkdir($storage_path, 0777, true);
}

// 获取RSS新闻
function fetch_news($rss_url) {
    $rss_content = @file_get_contents($rss_url);
    if ($rss_content === false) {
        return ['error' => '无法获取RSS内容'];
    }
    
    $xml = simplexml_load_string($rss_content);
    $news_items = [];
    
    foreach ($xml->channel->item as $item) {
        $news_items[] = [
            'title' => (string)$item->title,
            'content' => (string)$item->description,
            'link' => (string)$item->link,
            'pubDate' => (string)$item->pubDate
        ];
    }
    
    return $news_items;
}

// 保存新闻为独立文件
function save_news($news, $storage_path) {
    foreach ($news as $item) {
        $filename = $storage_path . md5($item['title']) . '.md';
        $content = "# " . $item['title'] . "\n\n";
        $content .= "发布日期: " . $item['pubDate'] . "\n\n";
        $content .= $item['content'] . "\n\n";
        $content .= "[原文链接](" . $item['link'] . ")";
        file_put_contents($filename, $content);
    }
}

// 通过emlog API发布文章
function publish_to_emlog($news, $api_url, $api_key) {
    foreach ($news as $item) {
        $post_data = [
            'title' => $item['title'],
            'content' => $item['content'] . "\n\n[原文链接](" . $item['link'] . ")",
            'api_key' => $api_key
        ];
        
        $ch = curl_init($api_url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        
        // 记录发布结果
        file_put_contents($storage_path . 'publish_log.txt', 
            date('Y-m-d H:i:s') . " - " . $item['title'] . ": " . $response . "\n", 
            FILE_APPEND
        );
    }
}

// 主程序
$news = fetch_news($rss_url);
if (isset($news['error'])) {
    echo $news['error'];
    exit;
}

save_news($news, $storage_path);
publish_to_emlog($news, $emlog_api_url, $emlog_api_key);
echo "新闻采集并发布完成!";
?>
html 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新闻采集管理</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <header>
        <h1>新闻采集与发布系统</h1>
    </header>
    <main>
        <button onclick="collectNews()">采集并发布新闻</button>
        <div id="status">等待操作...</div>
        <ul id="news-list"></ul>
    </main>
    <script src="script.js"></script>
</body>
</html>
css 复制代码
body {
    font-family: Arial, sans-serif;
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}

header {
    text-align: center;
    margin-bottom: 20px;
}

button {
    padding: 10px 20px;
    background-color: #007bff;
    color: white;
    border: none;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}

#status {
    margin: 20px 0;
    padding: 10px;
    background-color: #f8f9fa;
    border-radius: 5px;
}

#news-list {
    list-style: none;
    padding: 0;
}

#news-list li {
    margin: 10px 0;
    padding: 10px;
    background-color: #e9ecef;
    border-radius: 5px;
}
javascript 复制代码
async function collectNews() {
    document.getElementById('status').textContent = '正在采集新闻...';
    try {
        const response = await fetch('news_collector.php');
        const result = await response.text();
        document.getElementById('status').textContent = result;
        
        // 显示已保存的新闻列表
        await fetchNewsList();
    } catch (error) {
        document.getElementById('status').textContent = '错误: ' + error.message;
    }
}

async function fetchNewsList() {
    const list = document.getElementById('news-list');
    list.innerHTML = '';
    
    // 假设有一个API端点返回已保存的新闻文件名
    const files = ['example1.md', 'example2.md']; // 这里应替换为实际的新闻文件列表
    files.forEach(file => {
        const li = document.createElement('li');
        li.textContent = file;
        list.appendChild(li);
    });
}

document.addEventListener('DOMContentLoaded', fetchNewsList);

使用说明

  1. 配置环境

    • 确保服务器支持PHP,并安装了cURL扩展。
    • news_collector.php中配置:
      • $emlog_api_url:您的emlog博客API地址。
      • $emlog_api_key:您的emlog API密钥。
      • $rss_url:目标新闻RSS源地址。
      • $storage_path:新闻文件存储目录(需有写权限)。
  2. 部署

    • 将上述文件上传到Web服务器。
    • 访问index.html以查看管理界面。
    • 点击"采集并发布新闻"按钮,触发news_collector.php执行采集和发布。
  3. 功能说明

    • 新闻采集:从指定的RSS源获取新闻标题、内容、链接和发布日期。
    • 文件存储:每篇新闻保存为独立的Markdown文件,文件名基于标题的MD5哈希。
    • emlog发布:通过emlog API将新闻发布为博客文章,包含原文链接。
    • 前端界面:提供简单的按钮触发采集,并显示已保存的新闻文件列表(需进一步实现文件列表API)。
  4. 注意事项

    • emlog API的具体实现可能需要根据官方文档调整publish_to_emlog函数。
    • RSS源需支持XML格式,若目标网站无RSS,可使用PHP的DOM解析器抓取网页内容(需额外实现)。
    • 确保news/目录有写权限。
    • 当前fetchNewsList中的文件列表为示例,需实现服务器端API以返回实际文件列表。
  5. 扩展建议

    • 添加定时任务(Cron Job)自动运行news_collector.php
    • 增强前端界面,支持预览新闻内容或手动选择发布。
    • 添加错误处理和日志记录,优化采集失败的处理逻辑。

如需进一步定制(例如特定RSS源解析、emlog API细节或前端功能增强),请提供更多细节,我可以为您调整代码!

相关推荐
元亓亓亓15 分钟前
SSM--day4--SpringMVC(补充)
java·后端·ssm
黄智勇28 分钟前
xlsx-handlebars 一个用于处理 XLSX 文件 Handlebars 模板的 Rust 库,支持多平台使
前端
沐雨橙风ιε1 小时前
Spring Boot整合Apache Shiro权限认证框架(应用篇)
java·spring boot·后端·apache shiro
考虑考虑1 小时前
fastjson调用is方法开头注意
java·后端·java ee
小蒜学长1 小时前
springboot基于javaweb的小零食销售系统的设计与实现(代码+数据库+LW)
java·开发语言·数据库·spring boot·后端
brzhang2 小时前
为什么 OpenAI 不让 LLM 生成 UI?深度解析 OpenAI Apps SDK 背后的新一代交互范式
前端·后端·架构
EnCi Zheng2 小时前
JPA 连接 PostgreSQL 数据库完全指南
java·数据库·spring boot·后端·postgresql
brzhang2 小时前
OpenAI Apps SDK ,一个好的 App,不是让用户知道它该怎么用,而是让用户自然地知道自己在做什么。
前端·后端·架构
LucianaiB2 小时前
从玩具到工业:基于 CodeBuddy code CLI 构建电力变压器绕组短路智能诊断系统
后端
井柏然3 小时前
前端工程化—实战npm包深入理解 external 及实例唯一性
前端·javascript·前端工程化