====== サイト内の新規Webページを調べてRSSで配信するPHP製フィード生成ツール - Feed Meister ====== {{:javascript:09_s.jpg|}} [[url-collector]]をエンジンとして、サイト内(同一ドメイン内)でリンクされているWebページを全て調べ、そのうち新しく作成されたページをピックアップしてRSS 2.0で配信するツールを作った。 DBからRSSを生成できないような静的なサイトで役に立つかもしれない。でもDBを使えるなら、DBのデータを直接RSSにした方が絶対楽だ。 ===== ライセンス ===== [[http://0-oo.net/pryn/MIT_license.txt|MITライセンス]]で。 ===== 使用例 ===== pickOut('http://example.co.jp/index.html', 'タイトルに共通の部分'); ===== ソースコード ===== _collector = new UrlCollector($interval); $this->_feed = $feedPath; $this->_list = $dataPath; $this->_count = $count; } /** * フィードを作成する * @param string $topUrl トップページのURL(この階層以下が蒐集対象になる) * @param string $titleTrim (省略可)タイトルから除外する文字列 * @param string $encoding (省略可)サイトの文字コード */ public function pickOut($topUrl, $titleTrim = '', $encoding = 'UTF-8') { $newArr = $this->_collector->getUrls($topUrl, $titleTrim, $encoding); $timeArr = $this->_update($newArr); arsort($timeArr); //更新日時の新しい順 $this->_writeFeed($newArr, $timeArr, $topUrl); } private function _update($newArr) { if (file_exists($this->_list)) { $oldArr = explode("\n", file_get_contents($this->_list)); $oldCnt = count($oldArr); } else { $oldCnt = 0; } $bookmark = 0; $now = time(); $timeArr = array(); $fp = fopen($this->_list, 'w'); foreach ($newArr as $url => $title) { $timestamp = 0; for ($i = $bookmark; $i < $oldCnt; $i++) { $old = explode("\t", $oldArr[$i]); if ($url > $old[0]) { //該当のURLを探す continue; } $bookmark = $i; if ($url == $old[0]) { //既存の場合 $bookmark++; $timestamp = $old[2]; } break; } if (!$timestamp) { $timestamp = $now; } fwrite($fp, $url . "\t" . $title . "\t" . $timestamp . "\n"); $timeArr[$url] = $timestamp; } fclose($fp); return $timeArr; } /** * RSS2.0のみ */ private function _writeFeed($newArr, $timeArr, $top) { $encoding = mb_internal_encoding(); if ($encoding == 'UTF-8') { $encoding = ''; } $fp = fopen($this->_feed, 'w'); fwrite($fp, '' . "\n"); fwrite($fp, '' . "\n"); fwrite($fp, "\n"); $title = $this->_convertTitle($newArr[$top], $encoding); fwrite($fp, "$title\n"); fwrite($fp, '' . htmlspecialchars($top, ENT_QUOTES) . "\n"); fwrite($fp, "$title\n"); fwrite($fp, "ja\n"); $i = 0; foreach ($timeArr as $url => $timestamp) { $title = $this->_convertTitle($newArr[$url], $encoding); fwrite($fp, "\n"); fwrite($fp, "$title\n"); fwrite($fp, '' . htmlspecialchars($url, ENT_QUOTES) . "\n"); fwrite($fp, '' . date('r', $timestamp) . "\n"); fwrite($fp, "\n"); $i++; if ($i > $this->_count) { break; } } fwrite($fp, "\n"); fwrite($fp, ""); fclose($fp); } private function _convertTitle($title, $encoding) { if ($encoding) { $title = mb_convert_encoding($title, 'UTF-8', $encoding); } return htmlspecialchars($title, ENT_QUOTES); } }