]> git.wh0rd.org - tt-rss.git/blob - classes/feedparser.php
add basic rss support
[tt-rss.git] / classes / feedparser.php
1 <?php
2 class FeedParser {
3 private $doc;
4 private $error;
5 private $items;
6 private $link;
7 private $title;
8 private $type;
9
10 const FEED_RDF = 0;
11 const FEED_RSS = 1;
12 const FEED_ATOM = 2;
13
14 function __construct($data) {
15 libxml_use_internal_errors(true);
16 libxml_clear_errors();
17 $this->doc = new DOMDocument();
18 $this->doc->loadXML($data);
19 $this->error = $this->format_error(libxml_get_last_error());
20 libxml_clear_errors();
21
22 $this->items = array();
23 }
24
25 function init() {
26 $root = $this->doc->firstChild;
27 $xpath = new DOMXPath($this->doc);
28 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
29
30 $root = $xpath->query("(//atom:feed|//channel)")->item(0);
31
32 if ($root) {
33 switch ($root->tagName) {
34 case "channel":
35 $this->type = $this::FEED_RSS;
36 break;
37 case "feed":
38 $this->type = $this::FEED_ATOM;
39 break;
40 default:
41 $this->error = "Unknown/unsupported feed type";
42 return;
43 }
44
45 switch ($this->type) {
46 case $this::FEED_ATOM:
47
48 $title = $xpath->query("//atom:feed/atom:title")->item(0);
49
50 if ($title) {
51 $this->title = $title->nodeValue;
52 }
53
54 $link = $xpath->query("//atom:feed/atom:link[not(@rel)]")->item(0);
55
56 if ($link && $link->hasAttributes()) {
57 $this->link = $link->getAttribute("href");
58 }
59
60 $articles = $xpath->query("//atom:entry");
61
62 foreach ($articles as $article) {
63 array_push($this->items, new FeedItem_Atom($article));
64 }
65
66 break;
67 case $this::FEED_RDF:
68
69 break;
70 case $this::FEED_RSS:
71
72 $title = $xpath->query("//channel/title")->item(0);
73
74 if ($title) {
75 $this->title = $title->nodeValue;
76 }
77
78 $link = $xpath->query("//channel/link")->item(0);
79
80 if ($link && $link->hasAttributes()) {
81 $this->link = $link->getAttribute("href");
82 }
83
84 $articles = $xpath->query("//channel/item");
85
86 foreach ($articles as $article) {
87 array_push($this->items, new FeedItem_RSS($article));
88 }
89
90 break;
91 }
92 }
93 }
94
95 function format_error($error) {
96 if ($error) {
97 return sprintf("LibXML error %s at line %d (column %d): %s",
98 $error->code, $error->line, $error->column,
99 $error->message);
100 } else {
101 return "";
102 }
103 }
104
105 function error() {
106 return $this->error;
107 }
108
109 function get_link() {
110 return $this->link;
111 }
112
113 function get_title() {
114 return $this->title;
115 }
116
117 function get_items() {
118 return $this->items;
119 }
120
121 } ?>