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

PHP 橋接 AJAX 跨域存取 RSS 內容實作指南

     編輯:PHP 綜合知識

跨域難題

瀏覽器同源策略禁止 AJAX 直接請求不同網域 RSS。解法:自架 PHP Proxy 代理請求,前端呼叫同域 Proxy,Proxy 取得遠端 RSS 回傳。

架構圖

[前端 JS] --AJAX--> [PHP Proxy (bridge/rss.php)] --HTTP--> [遠端 RSS Feed]
     ▲                                                                    │
     └------------------ JSON/XML 回傳 -----------------------------------┘

PHP Proxy 實作 (bridge/rss.php)

addServer('127.0.0.1', 11211);
$xml = $mem->get($cacheKey);

if ($xml === false) {
    // 設定合理超時
    $ctx = stream_context_create([
        'http' => [
            'timeout' => 10,
            'user_agent' => 'MyRSSAggregator/1.0 (+https://example.com)',
            'follow_location' => 1,
            'max_redirects' => 3,
        ],
        'ssl' => ['verify_peer' => true, 'verify_peer_name' => true]
    ]);
    $xml = @file_get_contents($feedUrl, false, $ctx);
    if ($xml === false) {
        http_response_code(502);
        exit('Failed to fetch feed');
    }
    // 簡易 XML 合法性檢查
    if (!str_starts_with(ltrim($xml), 'set($cacheKey, $xml, 300); // 快取 5 分鐘
}

// 輸出
header('Content-Type: application/xml; charset=utf-8');
header('Cache-Control: public, max-age=300');
echo $xml;

前端 AJAX 呼叫 (jQuery/原生)

// 使用 fetch (現代)
async function loadFeed(feedUrl) {
    const proxy = '/bridge/rss.php?feed=' + encodeURIComponent(feedUrl);
    const resp = await fetch(proxy);
    if (!resp.ok) throw new Error('Proxy error: ' + resp.status);
    const text = await resp.text();
    const parser = new DOMParser();
    const xml = parser.parseFromString(text, 'application/xml');
    // 解析 xml...
}

// 或使用 jQuery
$.ajax({
    url: '/bridge/rss.php',
    data: {feed: feedUrl},
    dataType: 'xml',
    success: function(xml) { /* 解析 */ }
});

RSS/Atom 解析要點

  • RSS 2.0:/rss/channel/item - title, link, description, pubDate, guid
  • Atom 1.0:/feed/entry - title, link[@href], summary/content, updated, id
  • 命名空間處理:registerXPathNamespace 或 DOMXPath
  • 日期標準化:DateTime::createFromFormat 處理 RFC 822 / ISO 8601
  • 內容清理:移除脚本、iframe、危險屬性,保留安全標籤

安全性強化清單

  • 白名單限制上游 Feed 域名
  • 請求超時、大小限制 (stream_context)
  • SSL 憑證驗證
  • 快取層降低上游負載、防濫用
  • 輸出 Content-Type 正確、防 XSS (前端解析時 sanitize)
  • 速率限制 (Token Bucket/Leaky Bucket)

現代替代:Server-Side Rendering / Edge Functions

  • Next.js getServerSideProps、Nuxt asyncData 伺服端預取
  • Cloudflare Workers / Vercel Edge Functions 部署 Proxy 邊緣節點
  • RSSHub 等開源聚合服務自架
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved