1 <?php
3 class rssReader{
5 public static $attributes = array(
6 'title','link','description','language','copyright','skipHours','timestamp',
7 'managingEditor','webMaster','pubDate','lastBuildDate','category',
8 'generator','docs','cloud','ttl','image','rating','textInput','skipDays');
10 public static function parseFeedFromUrl($urls)
11 {
12 // We support multiple urls at once.
13 if(!is_array($urls)) $urls = array($urls);
14 foreach($urls as $url){
15 $doc = new DOMDocument();
16 $res = $doc->load($url);
17 if(!$res){
18 trigger_error("Failed to load feed '{$url}'!");
19 }else{
20 return(self::docToFeedEntries($doc, $url));
21 }
22 }
23 return(array());
24 }
26 public static function parseFeedFromSource($sources)
27 {
28 // We support multiple urls at once.
29 if(!is_array($sources)) $urls = array($sources);
30 foreach($sources as $source){
31 $doc = new DOMDocument();
32 $res = $doc->loadHTML($source);
33 if(!$res){
34 trigger_error("Failed to load feed '{$source}'!");
35 }else{
36 return(self::docToFeedEntries($doc, 'from source'));
37 }
38 }
39 return(array());
40 }
43 private static function docToFeedEntries($doc, $url)
44 {
45 $entries = array();
46 foreach ($doc->getElementsByTagName('item') as $item) {
48 // Collect data from feed
49 $entry = array();
50 $entry['url'] = $url;
51 foreach(self::$attributes as $attr){
52 $entry[$attr] =NULL;
53 $obj = $item->getElementsByTagName($attr);
54 if(is_object($obj->item(0))){
55 $entry[$attr] = $obj->item(0)->nodeValue;
56 }
57 }
59 // Fake timestamp in none is given.
60 if($entry['pubDate'] == NULL){
61 $entry['timestamp'] = NULL;
62 }else{
64 // Create an entry timestamp
65 $entry['timestamp'] = strtotime($entry['pubDate']);
66 }
67 $entries[] = $entry;
68 }
69 return($entries);
70 }
72 public static function sortFeedResultBy($feedRes , $sortBy = 'timestamp')
73 {
75 // Do not try to sort for invalid attributes.
76 if(!in_array($sortBy, self::$attributes)){
77 trigger_error("Invalid sortby attribute '{$sortBy}'!");
78 return($feedRes);
79 }
81 // Prepare feeds to be sorted, put them in an array indexed by the 'sortBy' attribute.
82 $data = array();
83 foreach($feedRes as $feed){
84 $key = "{$feed[$sortBy]}";
85 $c = '1';
86 while(empty($key) || isset($data[$key])){
87 $key = "{$c}_{$feed[$sortBy]}";
88 $c++;
89 }
90 $data[$key] = $feed;
91 }
93 // Sort the natural way and return the results.
94 uksort($data, 'strnatcasecmp');
95 return($data);
96 }
98 }
100 ?>