新闻自动采集并通过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细节或前端功能增强),请提供更多细节,我可以为您调整代码!

相关推荐
蓝婷儿13 分钟前
每天一个前端小知识 Day 28 - Web Workers / 多线程模型在前端中的应用实践
前端
琹箐13 分钟前
Ant ASpin自定义 indicator 报错
前端·javascript·typescript
小小小小小惠18 分钟前
Responsetype blob会把接口接收的二进制文件转换成blob格式
前端·javascript
爱电摇的小码农18 分钟前
【深度探究系列(5)】:前端开发打怪升级指南:从踩坑到封神的解决方案手册
前端·javascript·css·vue.js·node.js·html5·xss
Apipost的同学们33 分钟前
AI时代的接口自动化优化实践:如何突破Postman的局限性
后端·ai·架构·postman·自定义函数·apipost·api+ai
kymjs张涛43 分钟前
零一开源|前沿技术周报 #7
android·前端·ios
爱编程的喵1 小时前
React入门实战:从静态渲染到动态状态管理
前端·javascript
Tttian6221 小时前
npm init vue@latestnpm error code ETIMEDOUT
前端·vue.js·npm
患得患失9491 小时前
【前端】【组件库开发】【原理】【无框架开发】现代网页弹窗开发指南:从基础到优化
前端
运维咖啡吧1 小时前
给朋友们分享个好消息 7天时间23.5k
前端·程序员·ai编程