首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 動態生成 Atom Feed 完整實戰:從需求分析到代碼實現

     編輯:PHP 綜合知識

什麼是 Atom?

Atom 是基於 XML 的 Web 內容聚合標準格式,解決 RSS 的局限:支持內容類型聲明(HTML/XHTML/純文本)、國際化(xml:lang)、標準化時間格式(RFC 3339 vs RSS 的 RFC 822)、擴展性更強。

為什麼選 PHP + MySQL + Atom?

  • PHP:動態生成 XML,語法靈活,開發高效
  • MySQL:免費、成熟、與 PHP 默契配合
  • Atom:開放標準,客戶端廣泛支持(Feed 閱讀器、聚合站點)

業務場景:垂釣報告聚合平台

將論壇垂釣報告生成 Atom Feed,用戶通過閱讀器訂閱,第三方站點可嵌入聚合,點擊標題跳回主站瀏覽完整內容並接觸漁具營銷——雙贏模式。

數據庫設計

CREATE TABLE fishing_reports (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content TEXT NOT NULL,
    author VARCHAR(100),
    location VARCHAR(200),
    catch_details TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    permalink VARCHAR(500)  -- 回鏈主站完整 URL
);

Atom Feed 生成核心代碼

<?php
header('Content-Type: application/atom+xml; charset=utf-8');
echo '<?xml version="1.0" encoding="utf-8"?>';
?>
<feed xmlns="https://www.w3.org/2005/Atom" xml:lang="zh-CN">
    <title>魚樂無窮 - 垂釣報告聚合</title>
    <subtitle>專業釣友實時分享,一站式垂釣資訊</subtitle>
    <link href="https://fishinhole.com/feed/atom" rel="self" />
    <link href="https://fishinhole.com/reports" rel="alternate" />
    <updated><?= date('c', strtotime($latestReport['updated_at'])) ?></updated>
    <id>https://fishinhole.com/feed/atom</id>
    <author>
        <name>FishInHole Team</name>
        <email>feed@fishinhole.com</email>
    </author>
    <?php foreach ($reports as $report): ?>
    <entry>
        <title><?= htmlspecialchars($report['title']) ?></title>
        <link href="<?= $report['permalink'] ?>"/>
        <id><?= $report['permalink'] ?></id>
        <updated><?= date('c', strtotime($report['updated_at'])) ?></updated>
        <published><?= date('c', strtotime($report['created_at'])) ?></published>
        <author><name><?= htmlspecialchars($report['author']) ?></name></author>
        <summary type="html"><?= htmlspecialchars($report['content']) ?></summary>
        <category term="<?= $report['location'] ?>"/>
    </entry>
    <?php endforeach; ?>
</feed>

關鍵合規點

  • 命名空間:xmlns="https://www.w3.org/2005/Atom"
  • 時間格式:date('c') 輸出 RFC 3339(如 2024-01-15T14:30:00+08:00)
  • 內容類型:type="html" 或 type="xhtml" 明確聲明
  • 唯一 ID:使用永久鏈接作為 <id>
  • 自引用鏈接:rel="self" 指向 Feed 自身

部署為 /feed/atom 路由,提交至 Feed 目錄、搜索引擎、社交平台,即可實現內容廣泛分發。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved