メインコンテンツまでスキップ
Version: Fegg 5.x

はじめに

サイトの投稿をRSS 2.0フィードとして書き出します

Fegg\Tool\FeedはRSS 2.0フィードを書き出します。フィードリーダーやほかのサイトが、このフィードでサイトの投稿を追えるようになります。(フィードを読み込むのはRSS、書き出すのがFeedです。)

使用方法​

スケルトンでは、News::feed()が最新のニュース投稿を/news/feed.xmlで配信しています。

htdocs/_fegg/site/src/Controller/News.php
use Fegg\Tool\Feed;

public function feed()
{
$siteName = $this->config['site_info']['name'];
$feed = new Feed('ニュース | ' . $siteName, '/news/', $siteName . 'のニュース', '/news/feed.xml');

$rows = $this->_model
->order('post_date', 'desc')
->order('news_id', 'desc')
->limit(20)
->all();
foreach ($rows as $row) {
$feed->add(array(
'title' => $row['title'],
'link' => '/news/post_' . $row['news_id'] . '.html',
'date' => $row['post_date'],
'category' => feggCategoryLabel($row['category'], 'news'),
// Saved through HtmlSanitizer::clean(); the description is made from it
'content' => $row['content'],
));
}

$feed->display();
}
htdocs/_fegg/site/config/route.php
$route['news/feed.xml'] = 'news/feed';

ニュースのコントローラーのモデルは公開ページ用(new Model(false, ...))なので、非表示の投稿はフィードに入りません。フィードの場所は、siteframeでブラウザーとフィードリーダーに知らせます。

htdocs/_fegg/site/template/main/tpl/template/siteframe.tpl
<link rel="alternate" type="application/rss+xml" title="{{ $site.name }}" href="{{ base_url }}/news/feed.xml">

出力の内容​

Output
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
<title>ニュース | Example</title>
<link>https://www.example.com/news/</link>
<description>Exampleのニュース</description>
<language>ja</language>
<lastBuildDate>Sun, 15 Nov 2026 10:00:00 +0900</lastBuildDate>
<atom:link href="https://www.example.com/news/feed.xml" rel="self" type="application/rss+xml"/>
<item>
<title>New shop</title>
<link>https://www.example.com/news/post_12.html</link>
<guid isPermaLink="true">https://www.example.com/news/post_12.html</guid>
<pubDate>Sun, 15 Nov 2026 10:00:00 +0900</pubDate>
<category>お知らせ</category>
<description>We open a new shop in Osaka.</description>
<content:encoded><![CDATA[<p>We open a <a href="https://www.example.com/shops/">new shop</a> in Osaka.</p>]]></content:encoded>
</item>
</channel>
</rss>
  • 本文から作る概要:descriptionがない場合は、本文のテキストを使います。タグ(<script>/<style>は中身ごと)を取り除き、エンティティを戻し、空白をまとめてから、240桁(全角1文字は2桁)に縮めて…を付けます。
  • 絶対URL:パス(link、フィードのリンクとURL)はfeggAbsoluteUrl()で絶対URLにします(絶対URLを参照)。フィードリーダーは相対パスを解決できないので、本文のsrc="/…"とhref="/…"にはスキームとホストを付けます。これらのパスにはベースパスがすでに入っている(エディターがそう書き出す)ので、付けるのはドメインだけです。
  • CDATA:本文は<content:encoded>に、CDATAセクションに入れたHTMLとして書き出します。本文に]]>があれば、2つのセクションに分けます。ほかのテキストはエスケープします。
  • XMLで使えない制御文字は取り除きます。
  • lastBuildDateは最新の投稿の日時です。言語はjaです。

本文には、表示しても安全な内容を渡してください。HtmlSanitizer::clean()を通して保存したCMSのリッチテキストがそれにあたります。

エラー​

  • タイトルもリンクもない投稿を追加したとき、リクエストがないのにパスを渡したとき(コマンドではFEGG_CURRENT_URLが設定されないので、完全なURLを渡します)、日付を読み取れないときは、\InvalidArgumentExceptionを投げます。

関数​