/mvc/components/rss
[return to app]1
<?php
2 /**
3 * RSS/Atom feed reader
4 */
5 class rssComponent {
6 /**
7 * A more forgiving extension of PHP's strtotime()
8 *
9 * @param str $date
10 * @return int
11 */
12 protected function _strtotime($date) {
13 $timestamp = strtotime($date);
14 if ($timestamp == -1) {
15 $date = str_replace('T', ' ', substr($date, 0, (strlen($date)-6)));
16 $lastDot = strrpos($date, '.');
17 if ($lastDot) {
18 $date = substr($date, 0, $lastDot);
19 }
20 $timestamp = strtotime($date);
21 }
22 return $timestamp;
23 }
24
25 /**
26 * Reads an RSS or Atom feed and returns the contents in a PHP array consisting of title, description, link
and
27 * date (if included.)
28 *
29 * @param str $url
30 * @return array
31 */
32 public function getFeed($url) {
33 $xml = simplexml_load_string(file_get_contents($url));
34 if (isset($xml->channel)) {
35 $items = $xml->channel->item;
36 $feedtype = 'rss2.0';
37 } else {
38 $items = $xml->entry;
39 $feedtype = 'atom';
40 }
41 foreach($items as $item) {
42 $title = $item->title;
43 if ($feedtype == 'rss2.0') {
44 $link = (isset($item->link) ? $item->link : $item->guid);
45 $description = (isset($item->description) ? $item->description
46 : current($item->xpath('content:encoded')));
47 $date = (isset($item->pubDate) ? $item->pubDate : current($item->xpath('dc:date')));
48 } else {
49 $link = $item->link['href'];
50 $description = (isset($item->content) ? $item->content : $item->summary);
51 $date = (isset($item->updated) ? $item->updated : $item->created);
52 }
53 $return = array('title' => trim($title), 'link' => trim($link), 'description' => trim($description));
54 if ($date) {
55 $timestamp = $this->_strtotime($date);
56 $return['date'] = date('Y-m-d H:i:s', $timestamp);
57 }
58 $data[] = $return;
59 }
60 return (isset($data) ? $data : array());
61 }
62 }