PHPでRSSを解析するメモ
ブログのRSSを解析して記事一覧を表示…とかをするためのメモ。
「RSS2.0と宣言されているのにデータの一部がAtomで配信されている。」とか時々あるので、宣言は信用せずに「それらしいデータがないか探す」という方針で実装。
feed_load_file()
を実行すれば、階層のある連想配列でデータをまとめて返すので、あとは表示するだけ…という仕様にしています。
<?php
$feed = feed_load_file('http://freo.jp/info/news/feed');
echo "<!DOCTYPE html>\n";
echo "<html lang=\"ja\">\n";
echo "<head>\n";
echo "<meta charset=\"utf-8\" />\n";
echo "<title>RSSの解析</title>\n";
echo "</head>\n";
echo "<body>\n";
if (empty($feed)) {
echo 'エラー';
} else {
echo '<strong>形式</strong>';
echo '<hr />';
echo $feed['type'];
echo '<hr />';
echo '<strong>概要</strong>';
echo '<hr />';
echo 'title : ' . $feed['channel']['title'] . '<br />';
echo 'link : ' . $feed['channel']['link'] . '<br />';
echo 'description : ' . $feed['channel']['description'] . '<br />';
echo '<hr />';
echo '<strong>記事</strong>';
echo '<hr />';
foreach ($feed['item'] as $item) {
if (strtotime($item['date']) > time()) {
continue;
}
echo 'title : ' . $item['title'] . '<br />';
echo 'link : ' . $item['link'] . '<br />';
echo 'description : ' . $item['description'] . '<br />';
echo 'content : ' . $item['content'] . '<br />';
echo 'date : ' . $item['date'] . '<br />';
echo '<hr />';
}
}
echo "</body>\n";
echo "</html>\n";
exit;
feed_load_file()
の内容は、長いので続きで。