1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect1 id="zend.feed.reader">
4 <title>Zend_Feed_Reader</title>
6 <sect2 id="zend.feed.reader.introduction">
7 <title>Introduction</title>
10 <classname>Zend_Feed_Reader</classname> is a component used to
11 consume <acronym>RSS</acronym> and Atom feeds of any version, including
12 <acronym>RDF</acronym>/<acronym>RSS</acronym> 1.0,
13 <acronym>RSS</acronym> 2.0 and Atom 0.3/1.0. The <acronym>API</acronym> for
14 retrieving feed data is
15 deliberately simple since <classname>Zend_Feed_Reader</classname> is
16 capable of searching any feed of any type for the information
17 requested through the <acronym>API</acronym>. If the typical elements containing this
18 information are not present, it will adapt and fall back on a
19 variety of alternative elements instead. This ability to choose from
20 alternatives removes the need for users to create their own
21 abstraction layer on top of the component to make it useful or have
22 any in-depth knowledge of the underlying standards, current
23 alternatives, and namespaced extensions.
27 Internally, <classname>Zend_Feed_Reader</classname> works almost
28 entirely on the basis of making XPath queries against the feed <acronym>XML</acronym>'s
29 Document Object Model. The <acronym>DOM</acronym> is not exposed though a chained
30 property <acronym>API</acronym> like <classname>Zend_Feed</classname> though the
31 underlying <classname>DOMDocument</classname>,
32 <classname>DOMElement</classname> and
33 <classname>DOMXPath</classname> objects are exposed for external
34 manipulation. This singular approach to parsing is consistent and
35 the component offers a plugin system to add to the Feed and Entry
36 level <acronym>API</acronym> by writing Extensions on a similar basis.
40 Performance is assisted in three ways. First of all,
41 <classname>Zend_Feed_Reader</classname> supports caching using
42 <classname>Zend_Cache</classname> to maintain a copy of the original
43 feed <acronym>XML</acronym>. This allows you to skip network requests for a feed
44 <acronym>URI</acronym> if
45 the cache is valid. Second, the Feed and Entry level <acronym>API</acronym> is backed
46 by an internal cache (non-persistant) so repeat <acronym>API</acronym> calls for the
47 same feed will avoid additional <acronym>DOM</acronym>/XPath use. Thirdly, importing
48 feeds from a <acronym>URI</acronym> can take advantage of
49 <acronym>HTTP</acronym> Conditional GET requests
50 which allow servers to issue an empty 304 response when the
51 requested feed has not changed since the last time you requested it.
52 In the final case, an instance of <classname>Zend_Cache</classname>
53 will hold the last received feed along with the ETag and
54 Last-Modified header values sent in the <acronym>HTTP</acronym> response.
58 In relation to <classname>Zend_Feed</classname>,
59 <classname>Zend_Feed_Reader</classname> was formulated as a free
60 standing replacement for <classname>Zend_Feed</classname> but it is
61 not backwards compatible with <classname>Zend_Feed</classname>.
62 Rather it is an alternative following a different ideology focused
63 on being simple to use, flexible, consistent and extendable through
64 the plugin system. <classname>Zend_Feed_Reader</classname> is also
65 not capable of constructing feeds and delegates this responsibility
66 to <classname>Zend_Feed_Writer</classname>, its sibling in arms.
70 <sect2 id="zend.feed.reader.import">
71 <title>Importing Feeds</title>
74 Importing a feed with <classname>Zend_Feed_Reader</classname> is not
75 that much different to <classname>Zend_Feed</classname>. Feeds can
76 be imported from a string, file, <acronym>URI</acronym> or an instance of type
77 <classname>Zend_Feed_Abstract</classname>. Importing from a <acronym>URI</acronym> can
78 additionally utilise a <acronym>HTTP</acronym> Conditional GET request. If importing
79 fails, an exception will be raised. The end result will be an object
80 of type <classname>Zend_Feed_Reader_FeedInterface</classname>, the
81 core implementations of which are
82 <classname>Zend_Feed_Reader_Feed_Rss</classname> and
83 <classname>Zend_Feed_Reader_Feed_Atom</classname>
84 (<classname>Zend_Feed</classname> took all the short names!). Both
85 objects support multiple (all existing) versions of these broad feed
90 In the following example, we import an <acronym>RDF</acronym>/<acronym>RSS</acronym> 1.0
91 feed and extract some basic information that can be saved to a database or
95 <programlisting language="php"><![CDATA[
96 $feed = Zend_Feed_Reader::import('http://www.planet-php.net/rdf/');
98 'title' => $feed->getTitle(),
99 'link' => $feed->getLink(),
100 'dateModified' => $feed->getDateModified(),
101 'description' => $feed->getDescription(),
102 'language' => $feed->getLanguage(),
103 'entries' => array(),
106 foreach ($feed as $entry) {
108 'title' => $entry->getTitle(),
109 'description' => $entry->getDescription(),
110 'dateModified' => $entry->getDateModified(),
111 'authors' => $entry->getAuthors(),
112 'link' => $entry->getLink(),
113 'content' => $entry->getContent()
115 $data['entries'][] = $edata;
120 The example above demonstrates
121 <classname>Zend_Feed_Reader</classname>'s <acronym>API</acronym>, and it also
122 demonstrates some of its internal operation. In reality, the <acronym>RDF</acronym>
123 feed selected does not have any native date or author elements,
124 however it does utilise the Dublin Core 1.1 module which offers
125 namespaced creator and date elements.
126 <classname>Zend_Feed_Reader</classname> falls back on these and
127 similar options if no relevant native elements exist. If it
128 absolutely cannot find an alternative it will return <constant>NULL</constant>,
129 indicating the information could not be found in the feed. You
130 should note that classes implementing
131 <classname>Zend_Feed_Reader_FeedInterface</classname> also implement
132 the <acronym>SPL</acronym> <classname>Iterator</classname> and
133 <classname>Countable</classname> interfaces.
137 Feeds can also be imported from strings, files, and even objects of
138 type <classname>Zend_Feed_Abstract</classname>.
141 <programlisting language="php"><![CDATA[
143 $feed = Zend_Feed_Reader::import('http://www.planet-php.net/rdf/');
146 $feed = Zend_Feed_Reader::importString($feedXmlString);
149 $feed = Zend_Feed_Reader::importFile('./feed.xml');
151 // from a Zend_Feed_Abstract object
152 $zfeed = Zend_Feed::import('http://www.planet-php.net/atom/');
153 $feed = Zend_Feed_Reader::importFeed($zfeed);
157 <sect2 id="zend.feed.reader.sources">
158 <title>Retrieving Underlying Feed and Entry Sources</title>
161 <classname>Zend_Feed_Reader</classname> does its best not to stick
162 you in a narrow confine. If you need to work on a feed outside of
163 <classname>Zend_Feed_Reader</classname>, you can extract the base
164 <classname>DOMDocument</classname> or
165 <classname>DOMElement</classname> objects from any class, or even an
166 <acronym>XML</acronym> string containing these. Also provided are methods to extract
167 the current <classname>DOMXPath</classname> object (with all core
168 and Extension namespaces registered) and the correct prefix used in
169 all XPath queries for the current Feed or Entry. The basic methods
170 to use (on any object) are <methodname>saveXml()</methodname>,
171 <methodname>getDomDocument()</methodname>,
172 <methodname>getElement()</methodname>,
173 <methodname>getXpath()</methodname> and
174 <methodname>getXpathPrefix()</methodname>. These will let you break
175 free of <classname>Zend_Feed_Reader</classname> and do whatever else
182 <methodname>saveXml()</methodname> returns an <acronym>XML</acronym> string
183 containing only the element representing the current object.
189 <methodname>getDomDocument()</methodname> returns the
190 <classname>DOMDocument</classname> object representing the
191 entire feed (even if called from an Entry object).
197 <methodname>getElement()</methodname> returns the
198 <classname>DOMElement</classname> of the current object
199 (i.e. the Feed or current Entry).
205 <methodname>getXpath()</methodname> returns the
206 <classname>DOMXPath</classname> object for the current feed
207 (even if called from an Entry object) with the namespaces of
208 the current feed type and all loaded Extensions
215 <methodname>getXpathPrefix()</methodname> returns the query
216 prefix for the current object (i.e. the Feed or current
217 Entry) which includes the correct XPath query path for that
218 specific Feed or Entry.
224 Here's an example where a feed might include an <acronym>RSS</acronym> Extension not
225 supported by <classname>Zend_Feed_Reader</classname> out of the box.
226 Notably, you could write and register an Extension (covered later)
227 to do this, but that's not always warranted for a quick check. You
228 must register any new namespaces on the
229 <classname>DOMXPath</classname> object before use unless they are
230 registered by <classname>Zend_Feed_Reader</classname> or an
231 Extension beforehand.
234 <programlisting language="php"><![CDATA[
235 $feed = Zend_Feed_Reader::import('http://www.planet-php.net/rdf/');
236 $xpathPrefix = $feed->getXpathPrefix();
237 $xpath = $feed->getXpath();
238 $xpath->registerNamespace('admin', 'http://webns.net/mvcb/');
239 $reportErrorsTo = $xpath->evaluate('string('
241 . '/admin:errorReportsTo)');
246 If you register an already registered namespace with a different
247 prefix name to that used internally by
248 <classname>Zend_Feed_Reader</classname>, it will break the
249 internal operation of this component.
254 <sect2 id="zend.feed.reader.cache-request">
255 <title>Cache Support and Intelligent Requests</title>
257 <sect3 id="zend.feed.reader.cache-request.cache">
258 <title>Adding Cache Support to Zend_Feed_Reader</title>
261 <classname>Zend_Feed_Reader</classname> supports using an
262 instance of <classname>Zend_Cache</classname> to cache feeds (as
263 <acronym>XML</acronym>) to avoid unnecessary network requests. Adding a cache is as
264 simple here as it is for other Zend Framework components, create
265 and configure your cache and then tell
266 <classname>Zend_Feed_Reader</classname> to use it! The cache key
267 used is "<classname>Zend_Feed_Reader_</classname>" followed by the
268 <acronym>MD5</acronym> hash of the feed's <acronym>URI</acronym>.
271 <programlisting language="php"><![CDATA[
272 $frontendOptions = array(
274 'automatic_serialization' => true
276 $backendOptions = array('cache_dir' => './tmp/');
277 $cache = Zend_Cache::factory(
278 'Core', 'File', $frontendOptions, $backendOptions
281 Zend_Feed_Reader::setCache($cache);
286 While it's a little off track, you should also consider
288 <classname>Zend_Loader_PluginLoader</classname> which is
289 used by <classname>Zend_Feed_Reader</classname> to load
295 <sect3 id="zend.feed.reader.cache-request.http-conditional-get">
296 <title>HTTP Conditional GET Support</title>
299 The big question often asked when importing a feed frequently, is
300 if it has even changed. With a cache enabled, you can add <acronym>HTTP</acronym>
301 Conditional GET support to your arsenal to answer that question.
305 Using this method, you can request feeds from <acronym>URI</acronym>s and include
306 their last known ETag and Last-Modified response header values
307 with the request (using the If-None-Match and If-Modified-Since
308 headers). If the feed on the server remains unchanged, you
309 should receive a 304 response which tells
310 <classname>Zend_Feed_Reader</classname> to use the cached
311 version. If a full feed is sent in a response with a status code
312 of 200, this means the feed has changed and
313 <classname>Zend_Feed_Reader</classname> will parse the new
314 version and save it to the cache. It will also cache the new
315 ETag and Last-Modified header values for future use.
319 These "conditional" requests are not guaranteed to be supported
320 by the server you request a <acronym>URI</acronym> of, but can be attempted
321 regardless. Most common feed sources like blogs should however
322 have this supported. To enable conditional requests, you will
323 need to provide a cache to <classname>Zend_Feed_Reader</classname>.
326 <programlisting language="php"><![CDATA[
327 $frontendOptions = array(
329 'automatic_serialization' => true
331 $backendOptions = array('cache_dir' => './tmp/');
332 $cache = Zend_Cache::factory(
333 'Core', 'File', $frontendOptions, $backendOptions
336 Zend_Feed_Reader::setCache($cache);
337 Zend_Feed_Reader::useHttpConditionalGet();
339 $feed = Zend_Feed_Reader::import('http://www.planet-php.net/rdf/');
343 In the example above, with <acronym>HTTP</acronym> Conditional GET requests enabled,
344 the response header values for ETag and Last-Modified will be cached
345 along with the feed. For the next 24hrs (the cache lifetime), feeds will
346 only be updated on the cache if a non-304 response is received
347 containing a valid <acronym>RSS</acronym> or Atom <acronym>XML</acronym> document.
351 If you intend on managing request headers from outside
352 <classname>Zend_Feed_Reader</classname>, you can set the
353 relevant If-None-Matches and If-Modified-Since request headers
354 via the <acronym>URI</acronym> import method.
357 <programlisting language="php"><![CDATA[
358 $lastEtagReceived = '5e6cefe7df5a7e95c8b1ba1a2ccaff3d';
359 $lastModifiedDateReceived = 'Wed, 08 Jul 2009 13:37:22 GMT';
360 $feed = Zend_Feed_Reader::import(
361 $uri, $lastEtagReceived, $lastModifiedDateReceived
367 <sect2 id="zend.feed.reader.locate">
368 <title>Locating Feed URIs from Websites</title>
371 These days, many websites are aware that the location of their <acronym>XML</acronym>
372 feeds is not always obvious. A small <acronym>RDF</acronym>, <acronym>RSS</acronym> or
373 Atom graphic helps when the user is reading the page, but what about when a machine
374 visits trying to identify where your feeds are located? To assist in
375 this, websites may point to their feeds using <link> tags in
376 the <head> section of their <acronym>HTML</acronym>. To take advantage of this,
377 you can use <classname>Zend_Feed_Reader</classname> to locate these
378 feeds using the static <methodname>findFeedLinks()</methodname>
383 This method calls any <acronym>URI</acronym> and searches for the location of
384 <acronym>RSS</acronym>, <acronym>RDF</acronym>
385 and Atom feeds assuming the website's <acronym>HTML</acronym> contains the relevant
386 links. It then returns a value object where you can check for the existence of a
387 <acronym>RSS</acronym>, <acronym>RDF</acronym> or Atom feed <acronym>URI</acronym>.
391 The returned object is an <classname>ArrayObject</classname> subclass
392 called <classname>Zend_Feed_Reader_Collection_FeedLink</classname> so you can cast
393 it to an array, or iterate over it, to access all the detected links.
394 However, as a simple shortcut, you can just grab the first RSS, RDF
395 or Atom link using its public properties as in the example below. Otherwise,
396 each element of the <classname>ArrayObject</classname> is a simple array
397 with the keys "type" and "uri" where the type is one of "rdf", "rss" or
401 <programlisting language="php"><![CDATA[
402 $links = Zend_Feed_Reader::findFeedLinks('http://www.planet-php.net');
404 if(isset($links->rdf)) {
405 echo $links->rdf, "\n"; // http://www.planet-php.org/rdf/
407 if(isset($links->rss)) {
408 echo $links->rss, "\n"; // http://www.planet-php.org/rss/
410 if(isset($links->atom)) {
411 echo $links->atom, "\n"; // http://www.planet-php.org/atom/
416 Based on these links, you can then import from whichever source you
417 wish in the usual manner.
421 This quick method only gives you one link for each feed type, but
422 websites may indicate many links of any type. Perhaps it's a news
423 site with a RSS feed for each news category. You can iterate over
424 all links using the ArrayObject's iterator.
427 <programlisting language="php"><![CDATA[
428 $links = Zend_Feed_Reader::findFeedLinks('http://www.planet-php.net');
430 foreach ($links as $link) {
431 echo $link['uri'], "\n";
436 <sect2 id="zend.feed.reader.attribute-collections">
437 <title>Attribute Collections</title>
440 In an attempt to simplify return types, with Zend Framework 1.10 return
441 types from the various feed and entry level methods may include an object
442 of type <classname>Zend_Feed_Reader_Collection_CollectionAbstract</classname>.
443 Despite the special class name which I'll explain below, this is just a simple
444 subclass of SPL's <classname>ArrayObject</classname>.
448 The main purpose here is to allow the presentation of as much data as possible
449 from the requested elements, while still allowing access to the most relevant
450 data as a simple array. This also enforces a standard approach to returning
451 such data which previously may have wandered between arrays and objects.
455 The new class type acts identically to <classname>ArrayObject</classname>
456 with the sole addition being a new method <methodname>getValues()</methodname>
457 which returns a simple flat array containing the most relevant information.
461 A simple example of this is
462 <methodname>Zend_Feed_Reader_FeedInterface::getCategories()</methodname>. When used with
463 any RSS or Atom feed, this method will return category data as a container object called
464 <classname>Zend_Feed_Reader_Collection_Category</classname>. The container object will
465 contain, per category, three fields of data: term, scheme and label. The "term" is the
466 basic category name, often machine readable (i.e. plays nice with URIs). The scheme
467 represents a categorisation scheme (usually a URI identifier) also known as a "domain"
468 in RSS 2.0. The "label" is a human readable category name which supports html entities.
469 In RSS 2.0, there is no label attribute so it is always set to the same value as the
470 term for convenience.
474 To access category labels by themselves in a simple value array,
475 you might commit to something like:
478 <programlisting language="php"><![CDATA[
479 $feed = Zend_Feed_Reader::import('http://www.example.com/atom.xml');
480 $categories = $feed->getCategories();
482 foreach ($categories as $cat) {
483 $labels[] = $cat['label']
488 It's a contrived example, but the point is that the labels are tied up with
493 However, the container class allows you to access the "most relevant" data
494 as a simple array using the <methodname>getValues()</methodname> method. The concept
495 of "most relevant" is obviously a judgement call. For categories it means the category
496 labels (not the terms or schemes) while for authors it would be the authors' names
497 (not their email addresses or URIs). The simple array is flat (just values) and passed
498 through <methodname>array_unique()</methodname> to remove duplication.
501 <programlisting language="php"><![CDATA[
502 $feed = Zend_Feed_Reader::import('http://www.example.com/atom.xml');
503 $categories = $feed->getCategories();
504 $labels = $categories->getValues();
508 The above example shows how to extract only labels and nothing else thus
509 giving simple access to the category labels without any additional work to extract
514 <sect2 id="zend.feed.reader.retrieve-info">
515 <title>Retrieving Feed Information</title>
518 Retrieving information from a feed (we'll cover entries/items in the
519 next section though they follow identical principals) uses a clearly
520 defined <acronym>API</acronym> which is exactly the same regardless of whether the feed
521 in question is <acronym>RSS</acronym>/<acronym>RDF</acronym>/Atom. The same goes for
522 sub-versions of these standards and we've tested every single
523 <acronym>RSS</acronym> and Atom version. While
524 the underlying feed <acronym>XML</acronym> can differ substantially in terms of the
525 tags and elements they present, they nonetheless are all trying to
526 convey similar information and to reflect this all the differences
527 and wrangling over alternative tags are handled internally by
528 <classname>Zend_Feed_Reader</classname> presenting you with an
529 identical interface for each. Ideally, you should not have to care
530 whether a feed is <acronym>RSS</acronym> or Atom so long as you can extract the
531 information you want.
536 While determining common ground between feed types is itself complex, it
537 should be noted that RSS in particular is a constantly disputed "specification".
538 This has its roots in the original RSS 2.0 document which contains ambiguities
539 and does not detail the correct treatment of all elements. As a result, this
540 component rigorously applies the RSS 2.0.11 Specification published by the
541 RSS Advisory Board and its accompanying RSS Best Practices Profile. No
542 other interpretation of RSS 2.0 will be supported though exceptions may
543 be allowed where it does not directly prevent the application of the two
544 documents mentioned above.
549 Of course, we don't live in an ideal world so there may be times the
550 <acronym>API</acronym> just does not cover what you're looking for. To assist you,
551 <classname>Zend_Feed_Reader</classname> offers a plugin system which
552 allows you to write Extensions to expand the core <acronym>API</acronym> and cover any
553 additional data you are trying to extract from feeds. If writing
554 another Extension is too much trouble, you can simply grab the
555 underlying <acronym>DOM</acronym> or XPath objects and do it by hand in your
556 application. Of course, we really do encourage writing an Extension
557 simply to make it more portable and reusable, and useful Extensions may be proposed
558 to the Framework for formal addition.
562 Here's a summary of the Core <acronym>API</acronym> for Feeds. You should note it
563 comprises not only the basic <acronym>RSS</acronym> and Atom standards, but also
564 accounts for a number of included Extensions bundled with
565 <classname>Zend_Feed_Reader</classname>. The naming of these
566 Extension sourced methods remain fairly generic - all Extension
567 methods operate at the same level as the Core <acronym>API</acronym> though we do allow
568 you to retrieve any specific Extension object separately if required.
572 <title>Feed Level API Methods</title>
577 <entry><methodname>getId()</methodname></entry>
578 <entry>Returns a unique ID associated with this feed</entry>
582 <entry><methodname>getTitle()</methodname></entry>
583 <entry>Returns the title of the feed</entry>
587 <entry><methodname>getDescription()</methodname></entry>
588 <entry>Returns the text description of the feed.</entry>
592 <entry><methodname>getLink()</methodname></entry>
595 Returns a <acronym>URI</acronym> to the <acronym>HTML</acronym> website
596 containing the same or
597 similar information as this feed (i.e. if the feed is from a blog,
598 it should provide the blog's <acronym>URI</acronym> where the
599 <acronym>HTML</acronym> version of the entries can be read).
604 <entry><methodname>getFeedLink()</methodname></entry>
607 Returns the <acronym>URI</acronym> of this feed, which may be the
608 same as the <acronym>URI</acronym> used to import the feed. There
609 are important cases where the feed link may differ because the source
610 URI is being updated and is intended to be removed in the future.
615 <entry><methodname>getAuthors()</methodname></entry>
618 Returns an object of type
619 <classname>Zend_Feed_Reader_Collection_Author</classname> which is an
620 <classname>ArrayObject</classname> whose elements are each simple arrays
621 containing any combination of the keys "name", "email" and "uri". Where
622 irrelevant to the source data, some of these keys may be omitted.
627 <entry><methodname>getAuthor(integer $index = 0)</methodname></entry>
630 Returns either the first author known, or with the
631 optional <varname>$index</varname> parameter any specific
632 index on the array of Authors as described above (returning
633 <constant>NULL</constant> if an invalid index).
638 <entry><methodname>getDateCreated()</methodname></entry>
641 Returns the date on which this feed was created. Generally
642 only applicable to Atom where it represents the date the resource
643 described by an Atom 1.0 document was created. The returned date
644 will be a <classname>Zend_Date</classname> object.
649 <entry><methodname>getDateModified()</methodname></entry>
652 Returns the date on which this feed was last modified. The returned date
653 will be a <classname>Zend_Date</classname> object.
658 <entry><methodname>getLanguage()</methodname></entry>
661 Returns the language of the feed (if defined) or simply the
662 language noted in the <acronym>XML</acronym> document.
667 <entry><methodname>getGenerator()</methodname></entry>
670 Returns the generator of the feed, e.g. the software which
671 generated it. This may differ between <acronym>RSS</acronym> and Atom
672 since Atom defines a different notation.
677 <entry><methodname>getCopyright()</methodname></entry>
678 <entry>Returns any copyright notice associated with the feed.</entry>
682 <entry><methodname>getHubs()</methodname></entry>
685 Returns an array of all Hub Server <acronym>URI</acronym> endpoints
686 which are advertised by the feed for use with the Pubsubhubbub
687 Protocol, allowing subscriptions to the feed for real-time updates.
692 <entry><methodname>getCategories()</methodname></entry>
695 Returns a <classname>Zend_Feed_Reader_Collection_Category</classname>
696 object containing the details of any categories associated with the
697 overall feed. The supported fields include "term" (the machine readable
698 category name), "scheme" (the categorisation scheme/domain for this
699 category), and "label" (a html decoded human readable category name).
700 Where any of the three fields are absent from the field, they are either
701 set to the closest available alternative or, in the case of "scheme",
702 set to <constant>NULL</constant>.
710 Given the variety of feeds in the wild, some of these methods will
711 undoubtedly return <constant>NULL</constant> indicating the relevant information
712 couldn't be located. Where possible, <classname>Zend_Feed_Reader</classname>
713 will fall back on alternative elements during its search. For
714 example, searching an <acronym>RSS</acronym> feed for a modification date is more
715 complicated than it looks. <acronym>RSS</acronym> 2.0 feeds should include a
716 <command><lastBuildDate></command> tag and (or) a
717 <command><pubDate></command> element. But what if it doesn't, maybe
718 this is an <acronym>RSS</acronym> 1.0 feed? Perhaps it instead has an
719 <command><atom:updated></command> element with identical information
720 (Atom may be used to supplement <acronym>RSS</acronym>'s syntax)? Failing that, we
721 could simply look at the entries, pick the most recent, and use its
722 <command><pubDate></command> element. Assuming it exists... Many
723 feeds also use Dublin Core 1.0/1.1 <command><dc:date></command>
724 elements for feeds and entries. Or we could find Atom lurking again.
728 The point is, <classname>Zend_Feed_Reader</classname> was designed
729 to know this. When you ask for the modification date (or anything
730 else), it will run off and search for all these alternatives until
731 it either gives up and returns <constant>NULL</constant>, or finds an
732 alternative that should have the right answer.
736 In addition to the above methods, all Feed objects implement methods
737 for retrieving the <acronym>DOM</acronym> and XPath objects for the current feeds as
738 described earlier. Feed objects also implement the <acronym>SPL</acronym> Iterator and
739 Countable interfaces. The extended <acronym>API</acronym> is summarised below.
743 <title>Extended Feed Level API Methods</title>
748 <entry><methodname>getDomDocument()</methodname></entry>
752 <classname>DOMDocument</classname> object for the
753 entire source <acronym>XML</acronym> document
758 <entry><methodname>getElement()</methodname></entry>
761 Returns the current feed level
762 <classname>DOMElement</classname> object
767 <entry><methodname>saveXml()</methodname></entry>
770 Returns a string containing an <acronym>XML</acronym> document of the
771 entire feed element (this is not the original
772 document but a rebuilt version)
777 <entry><methodname>getXpath()</methodname></entry>
780 Returns the <classname>DOMXPath</classname> object
781 used internally to run queries on the
782 <classname>DOMDocument</classname> object (this
783 includes core and Extension namespaces
789 <entry><methodname>getXpathPrefix()</methodname></entry>
792 Returns the valid <acronym>DOM</acronym> path prefix prepended
793 to all XPath queries matching the feed being queried
798 <entry><methodname>getEncoding()</methodname></entry>
801 Returns the encoding of the source <acronym>XML</acronym> document
802 (note: this cannot account for errors such as the
803 server sending documents in a different encoding). Where not
804 defined, the default UTF-8 encoding of Unicode is applied.
809 <entry><methodname>count()</methodname></entry>
812 Returns a count of the entries or items this feed contains
813 (implements <acronym>SPL</acronym> <classname>Countable</classname>
819 <entry><methodname>current()</methodname></entry>
822 Returns either the current entry (using the current index
823 from <methodname>key()</methodname>)
828 <entry><methodname>key()</methodname></entry>
829 <entry>Returns the current entry index</entry>
833 <entry><methodname>next()</methodname></entry>
834 <entry>Increments the entry index value by one</entry>
838 <entry><methodname>rewind()</methodname></entry>
839 <entry>Resets the entry index to 0</entry>
843 <entry><methodname>valid()</methodname></entry>
846 Checks that the current entry index is valid, i.e.
847 it does fall below 0 and does not exceed the number
853 <entry><methodname>getExtensions()</methodname></entry>
856 Returns an array of all Extension objects loaded for
857 the current feed (note: both feed-level and entry-level Extensions
858 exist, and only feed-level Extensions are returned here).
859 The array keys are of the form {ExtensionName}_Feed.
864 <entry><methodname>getExtension(string $name)</methodname></entry>
867 Returns an Extension object for the feed registered under the
868 provided name. This allows more fine-grained access to
869 Extensions which may otherwise be hidden within the implementation
870 of the standard <acronym>API</acronym> methods.
875 <entry><methodname>getType()</methodname></entry>
878 Returns a static class constant (e.g.
879 <constant>Zend_Feed_Reader::TYPE_ATOM_03</constant>,
880 i.e. Atom 0.3) indicating exactly what kind of feed
889 <sect2 id="zend.feed.reader.entry">
890 <title>Retrieving Entry/Item Information</title>
893 Retrieving information for specific entries or items (depending on
894 whether you speak Atom or <acronym>RSS</acronym>) is identical to feed level data.
895 Accessing entries is simply a matter of iterating over a Feed object
896 or using the <acronym>SPL</acronym> <classname>Iterator</classname> interface Feed
897 objects implement and calling the appropriate method on each.
901 <title>Entry Level API Methods</title>
906 <entry><methodname>getId()</methodname></entry>
907 <entry>Returns a unique ID for the current entry.</entry>
911 <entry><methodname>getTitle()</methodname></entry>
912 <entry>Returns the title of the current entry.</entry>
916 <entry><methodname>getDescription()</methodname></entry>
917 <entry>Returns a description of the current entry.</entry>
921 <entry><methodname>getLink()</methodname></entry>
924 Returns a <acronym>URI</acronym> to the <acronym>HTML</acronym> version
925 of the current entry.
930 <entry><methodname>getPermaLink()</methodname></entry>
933 Returns the permanent link to the current entry. In most cases,
934 this is the same as using <methodname>getLink()</methodname>.
939 <entry><methodname>getAuthors()</methodname></entry>
942 Returns an object of type
943 <classname>Zend_Feed_Reader_Collection_Author</classname> which is an
944 <classname>ArrayObject</classname> whose elements are each simple arrays
945 containing any combination of the keys "name", "email" and "uri". Where
946 irrelevant to the source data, some of these keys may be omitted.
951 <entry><methodname>getAuthor(integer $index = 0)</methodname></entry>
954 Returns either the first author known, or with the
955 optional <varname>$index</varname> parameter any specific
956 index on the array of Authors as described above (returning
957 <constant>NULL</constant> if an invalid index).
962 <entry><methodname>getDateCreated()</methodname></entry>
965 Returns the date on which the current entry was
966 created. Generally only applicable to Atom where it
967 represents the date the resource described by an
968 Atom 1.0 document was created.
973 <entry><methodname>getDateModified()</methodname></entry>
976 Returns the date on which the current entry was last
982 <entry><methodname>getContent()</methodname></entry>
985 Returns the content of the current entry (this has any
986 entities reversed if possible assuming the content type is
987 <acronym>HTML</acronym>). The description is returned if a
988 separate content element does not exist.
993 <entry><methodname>getEnclosure()</methodname></entry>
996 Returns an array containing the value of all
997 attributes from a multi-media <enclosure> element including
998 as array keys: <emphasis>url</emphasis>,
999 <emphasis>length</emphasis>, <emphasis>type</emphasis>.
1000 In accordance with the RSS Best Practices Profile of the RSS
1001 Advisory Board, no support is offers for multiple enclosures
1002 since such support forms no part of the RSS specification.
1007 <entry><methodname>getCommentCount()</methodname></entry>
1010 Returns the number of comments made on this entry at the
1011 time the feed was last generated
1016 <entry><methodname>getCommentLink()</methodname></entry>
1019 Returns a <acronym>URI</acronym> pointing to the <acronym>HTML</acronym>
1020 page where comments can be made on this entry
1026 <methodname>getCommentFeedLink([string $type =
1027 'atom'|'rss'])</methodname>
1031 Returns a <acronym>URI</acronym> pointing to a feed of the provided type
1032 containing all comments for this entry (type defaults to
1033 Atom/<acronym>RSS</acronym> depending on current feed type).
1038 <entry><methodname>getCategories()</methodname></entry>
1041 Returns a <classname>Zend_Feed_Reader_Collection_Category</classname>
1042 object containing the details of any categories associated with the
1043 entry. The supported fields include "term" (the machine readable
1044 category name), "scheme" (the categorisation scheme/domain for this
1045 category), and "label" (a html decoded human readable category name).
1046 Where any of the three fields are absent from the field, they are either
1047 set to the closest available alternative or, in the case of "scheme",
1048 set to <constant>NULL</constant>.
1056 The extended <acronym>API</acronym> for entries is identical to that for feeds with the
1057 exception of the Iterator methods which are not needed here.
1062 There is often confusion over the concepts of modified and
1063 created dates. In Atom, these are two clearly defined concepts
1064 (so knock yourself out) but in <acronym>RSS</acronym> they are vague.
1065 <acronym>RSS</acronym> 2.0
1066 defines a single <emphasis><pubDate></emphasis> element
1067 which typically refers to the date this entry was published,
1068 i.e. a creation date of sorts. This is not always the case, and
1069 it may change with updates or not. As a result, if you really
1070 want to check whether an entry has changed, don't rely on the
1071 results of <methodname>getDateModified()</methodname>. Instead,
1072 consider tracking the <acronym>MD5</acronym> hash of three other elements
1073 concatenated, e.g. using <methodname>getTitle()</methodname>,
1074 <methodname>getDescription()</methodname> and
1075 <methodname>getContent()</methodname>. If the entry was truly
1076 updated, this hash computation will give a different result than
1077 previously saved hashes for the same entry. This is obviously
1078 content oriented, and will not assist in detecting changes to other
1079 relevant elements. Atom feeds should not require such steps.
1083 Further muddying the
1084 waters, dates in feeds may follow different standards. Atom and
1085 Dublin Core dates should follow <acronym>ISO</acronym> 8601,
1086 and <acronym>RSS</acronym> dates should
1087 follow <acronym>RFC</acronym> 822 or <acronym>RFC</acronym> 2822
1088 which is also common. Date methods
1089 will throw an exception if <classname>Zend_Date</classname>
1090 cannot load the date string using one of the above standards, or the
1091 <acronym>PHP</acronym> recognised possibilities for <acronym>RSS</acronym> dates.
1097 The values returned from these methods are not validated. This
1098 means users must perform validation on all retrieved data
1099 including the filtering of any <acronym>HTML</acronym> such as from
1100 <methodname>getContent()</methodname> before it is output from
1101 your application. Remember that most feeds come from external
1102 sources, and therefore the default assumption should be that
1103 they cannot be trusted.
1108 <title>Extended Entry Level API Methods</title>
1113 <entry><methodname>getDomDocument()</methodname></entry>
1117 <classname>DOMDocument</classname> object for the
1118 entire feed (not just the current entry)
1123 <entry><methodname>getElement()</methodname></entry>
1126 Returns the current entry level
1127 <classname>DOMElement</classname> object
1132 <entry><methodname>getXpath()</methodname></entry>
1135 Returns the <classname>DOMXPath</classname> object
1136 used internally to run queries on the
1137 <classname>DOMDocument</classname> object (this
1138 includes core and Extension namespaces
1144 <entry><methodname>getXpathPrefix()</methodname></entry>
1147 Returns the valid <acronym>DOM</acronym> path prefix prepended
1148 to all XPath queries matching the entry being queried
1153 <entry><methodname>getEncoding()</methodname></entry>
1156 Returns the encoding of the source <acronym>XML</acronym> document
1157 (note: this cannot account for errors such as the server sending
1158 documents in a different encoding). The default encoding applied
1159 in the absence of any other is the UTF-8 encoding of Unicode.
1164 <entry><methodname>getExtensions()</methodname></entry>
1167 Returns an array of all Extension objects loaded for
1168 the current entry (note: both feed-level and entry-level
1169 Extensions exist, and only entry-level Extensions are returned
1170 here). The array keys are in the form {ExtensionName}_Entry.
1175 <entry><methodname>getExtension(string $name)</methodname></entry>
1178 Returns an Extension object for the entry registered under the
1179 provided name. This allows more fine-grained access to
1180 Extensions which may otherwise be hidden within the implementation
1181 of the standard <acronym>API</acronym> methods.
1186 <entry><methodname>getType()</methodname></entry>
1189 Returns a static class constant (e.g.
1190 <constant>Zend_Feed_Reader::TYPE_ATOM_03</constant>,
1191 i.e. Atom 0.3) indicating exactly what kind
1192 of feed is being consumed.
1200 <sect2 id="zend.feed.reader.extending">
1201 <title>Extending Feed and Entry APIs</title>
1204 Extending <classname>Zend_Feed_Reader</classname> allows you to add
1205 methods at both the feed and entry level which cover the retrieval
1206 of information not already supported by
1207 <classname>Zend_Feed_Reader</classname>. Given the number of
1208 <acronym>RSS</acronym> and
1209 Atom extensions that exist, this is a good thing since
1210 <classname>Zend_Feed_Reader</classname> couldn't possibly add
1215 There are two types of Extensions possible, those which retrieve
1216 information from elements which are immediate children of the root
1217 element (e.g. <command><channel></command> for <acronym>RSS</acronym> or
1218 <command><feed></command> for Atom) and those who retrieve
1219 information from child elements of an entry (e.g.
1220 <command><item></command> for <acronym>RSS</acronym> or
1221 <command><entry></command> for Atom). On the filesystem these are grouped as
1222 classes within a namespace based on the extension standard's name. For example,
1223 internally we have <classname>Zend_Feed_Reader_Extension_DublinCore_Feed</classname>
1224 and <classname>Zend_Feed_Reader_Extension_DublinCore_Entry</classname>
1225 classes which are two Extensions implementing Dublin Core
1226 1.0 and 1.1 support.
1230 Extensions are loaded into <classname>Zend_Feed_Reader</classname>
1231 using <classname>Zend_Loader_PluginLoader</classname>, so their operation
1232 will be familiar from other Zend Framework components.
1233 <classname>Zend_Feed_Reader</classname> already bundles a number of
1234 these Extensions, however those which are not used internally and
1235 registered by default (so called Core Extensions) must be registered
1236 to <classname>Zend_Feed_Reader</classname> before they are used. The
1237 bundled Extensions include:
1241 <title>Core Extensions (pre-registered)</title>
1246 <entry>DublinCore (Feed and Entry)</entry>
1249 Implements support for Dublin Core Metadata Element Set 1.0 and 1.1
1254 <entry>Content (Entry only)</entry>
1255 <entry>Implements support for Content 1.0</entry>
1259 <entry>Atom (Feed and Entry)</entry>
1260 <entry>Implements support for Atom 0.3 and Atom 1.0</entry>
1264 <entry>Slash</entry>
1267 Implements support for the Slash <acronym>RSS</acronym> 1.0 module
1272 <entry>WellFormedWeb</entry>
1273 <entry>Implements support for the Well Formed Web CommentAPI 1.0</entry>
1277 <entry>Thread</entry>
1280 Implements support for Atom Threading Extensions as described
1281 in <acronym>RFC</acronym> 4685
1286 <entry>Podcast</entry>
1289 Implements support for the Podcast 1.0 <constant>DTD</constant> from
1298 The Core Extensions are somewhat special since they are extremely
1299 common and multi-faceted. For example, we have a Core Extension for Atom.
1300 Atom is implemented as an Extension (not just a base class) because it
1301 doubles as a valid <acronym>RSS</acronym> module - you can insert
1302 Atom elements into <acronym>RSS</acronym> feeds. I've even seen
1303 <acronym>RDF</acronym> feeds which use a lot of Atom in place of more
1304 common Extensions like Dublin Core.
1308 <title>Non-Core Extensions (must register manually)</title>
1313 <entry>Syndication</entry>
1316 Implements Syndication 1.0 support for <acronym>RSS</acronym> feeds
1321 <entry>CreativeCommons</entry>
1324 A <acronym>RSS</acronym> module that adds an element at the
1325 <channel> or <item> level that specifies which Creative
1326 Commons license applies.
1334 The additional non-Core Extensions are offered but not registered to
1335 <classname>Zend_Feed_Reader</classname> by default. If you want to
1336 use them, you'll need to tell
1337 <classname>Zend_Feed_Reader</classname> to load them in advance of
1338 importing a feed. Additional non-Core Extensions will be included
1339 in future iterations of the component.
1343 Registering an Extension with
1344 <classname>Zend_Feed_Reader</classname>, so it is loaded and its <acronym>API</acronym>
1345 is available to Feed and Entry objects, is a simple affair using the
1346 <classname>Zend_Loader_PluginLoader</classname>. Here we register
1347 the optional Slash Extension, and discover that it can be directly
1348 called from the Entry level <acronym>API</acronym> without any effort. Note that
1349 Extension names are case sensitive and use camel casing for multiple
1353 <programlisting language="php"><![CDATA[
1354 Zend_Feed_Reader::registerExtension('Syndication');
1355 $feed = Zend_Feed_Reader::import('http://rss.slashdot.org/Slashdot/slashdot');
1356 $updatePeriod = $feed->current()->getUpdatePeriod();
1357 ]]></programlisting>
1360 In the simple example above, we checked how frequently a feed is being updated
1361 using the <methodname>getUpdatePeriod()</methodname>
1362 method. Since it's not part of
1363 <classname>Zend_Feed_Reader</classname>'s core <acronym>API</acronym>, it could only be
1364 a method supported by the newly registered Syndication Extension.
1368 As you can also notice, the new methods from Extensions are accessible from the main
1369 <acronym>API</acronym> using <acronym>PHP</acronym>'s magic methods. As an alternative,
1370 you can also directly access any Extension object for a similar result as seen below.
1373 <programlisting language="php"><![CDATA[
1374 Zend_Feed_Reader::registerExtension('Syndication');
1375 $feed = Zend_Feed_Reader::import('http://rss.slashdot.org/Slashdot/slashdot');
1376 $syndication = $feed->getExtension('Syndication');
1377 $updatePeriod = $syndication->getUpdatePeriod();
1378 ]]></programlisting>
1380 <sect3 id="zend.feed.reader.extending.feed">
1381 <title>Writing Zend_Feed_Reader Extensions</title>
1384 Inevitably, there will be times when the
1385 <classname>Zend_Feed_Reader</classname> <acronym>API</acronym> is just not capable
1386 of getting something you need from a feed or entry. You can use
1387 the underlying source objects, like
1388 <classname>DOMDocument</classname>, to get these by hand however
1389 there is a more reusable method available by writing Extensions
1390 supporting these new queries.
1394 As an example, let's take the case of a purely fictitious
1395 corporation named Jungle Books. Jungle Books have been
1396 publishing a lot of reviews on books they sell (from external
1397 sources and customers), which are distributed as an <acronym>RSS</acronym> 2.0
1398 feed. Their marketing department realises that web applications
1399 using this feed cannot currently figure out exactly what book is
1400 being reviewed. To make life easier for everyone, they determine
1401 that the geek department needs to extend <acronym>RSS</acronym> 2.0 to include a
1402 new element per entry supplying the <acronym>ISBN</acronym>-10 or
1403 <acronym>ISBN</acronym>-13 number of
1404 the publication the entry concerns. They define the new
1405 <command><isbn></command> element quite simply with a standard
1406 name and namespace <acronym>URI</acronym>:
1409 <programlisting language="php"><![CDATA[
1411 http://example.com/junglebooks/rss/module/1.0/
1412 ]]></programlisting>
1415 A snippet of <acronym>RSS</acronym> containing this extension in practice could be
1416 something similar to:
1419 <programlisting language="php"><![CDATA[
1420 <?xml version="1.0" encoding="utf-8" ?>
1422 xmlns:content="http://purl.org/rss/1.0/modules/content/"
1423 xmlns:jungle="http://example.com/junglebooks/rss/module/1.0/">
1425 <title>Jungle Books Customer Reviews</title>
1426 <link>http://example.com/junglebooks</link>
1427 <description>Many book reviews!</description>
1428 <pubDate>Fri, 26 Jun 2009 19:15:10 GMT</pubDate>
1430 http://example.com/junglebooks/book/938
1431 </jungle:dayPopular>
1433 <title>Review Of Flatland: A Romance of Many Dimensions</title>
1434 <link>http://example.com/junglebooks/review/987</link>
1435 <author>Confused Physics Student</author>
1439 <pubDate>Thu, 25 Jun 2009 20:03:28 -0700</pubDate>
1440 <jungle:isbn>048627263X</jungle:isbn>
1444 ]]></programlisting>
1447 Implementing this new <acronym>ISBN</acronym> element as a simple entry level
1448 extension would require the following class (using your own class
1449 namespace outside of Zend).
1452 <programlisting language="php"><![CDATA[
1453 class My_FeedReader_Extension_JungleBooks_Entry
1454 extends Zend_Feed_Reader_Extension_EntryAbstract
1456 public function getIsbn()
1458 if (isset($this->_data['isbn'])) {
1459 return $this->_data['isbn'];
1461 $isbn = $this->_xpath->evaluate(
1462 'string(' . $this->getXpathPrefix() . '/jungle:isbn)'
1467 $this->_data['isbn'] = $isbn;
1468 return $this->_data['isbn'];
1471 protected function _registerNamespaces()
1473 $this->_xpath->registerNamespace(
1474 'jungle', 'http://example.com/junglebooks/rss/module/1.0/'
1478 ]]></programlisting>
1481 This extension is easy enough to follow. It creates a new method
1482 <methodname>getIsbn()</methodname> which runs an XPath query on
1483 the current entry to extract the <acronym>ISBN</acronym> number enclosed by the
1484 <command><jungle:isbn></command> element. It can optionally
1485 store this to the internal non-persistent cache (no need to keep
1486 querying the <acronym>DOM</acronym> if it's called again on the same entry). The
1487 value is returned to the caller. At the end we have a protected
1488 method (it's abstract so it must exist) which registers the
1489 Jungle Books namespace for their custom <acronym>RSS</acronym> module. While we
1490 call this an <acronym>RSS</acronym> module, there's nothing to prevent the same
1491 element being used in Atom feeds - and all Extensions which use
1492 the prefix provided by <methodname>getXpathPrefix()</methodname>
1493 are actually neutral and work on <acronym>RSS</acronym> or Atom feeds with no
1498 Since this Extension is stored outside of Zend Framework, you'll
1499 need to register the path prefix for your Extensions so
1500 <classname>Zend_Loader_PluginLoader</classname> can find them.
1501 After that, it's merely a matter of registering the Extension,
1502 if it's not already loaded, and using it in practice.
1505 <programlisting language="php"><![CDATA[
1506 if(!Zend_Feed_Reader::isRegistered('JungleBooks')) {
1507 Zend_Feed_Reader::addPrefixPath(
1508 '/path/to/My/FeedReader/Extension', 'My_FeedReader_Extension'
1510 Zend_Feed_Reader::registerExtension('JungleBooks');
1512 $feed = Zend_Feed_Reader::import('http://example.com/junglebooks/rss');
1514 // ISBN for whatever book the first entry in the feed was concerned with
1515 $firstIsbn = $feed->current()->getIsbn();
1516 ]]></programlisting>
1519 Writing a feed level Extension is not much different. The
1520 example feed from earlier included an unmentioned
1521 <command><jungle:dayPopular></command> element which Jungle
1522 Books have added to their standard to include a link to the
1523 day's most popular book (in terms of visitor traffic). Here's
1524 an Extension which adds a
1525 <methodname>getDaysPopularBookLink()</methodname> method to the
1526 feel level <acronym>API</acronym>.
1529 <programlisting language="php"><![CDATA[
1530 class My_FeedReader_Extension_JungleBooks_Feed
1531 extends Zend_Feed_Reader_Extension_FeedAbstract
1533 public function getDaysPopularBookLink()
1535 if (isset($this->_data['dayPopular'])) {
1536 return $this->_data['dayPopular'];
1538 $dayPopular = $this->_xpath->evaluate(
1539 'string(' . $this->getXpathPrefix() . '/jungle:dayPopular)'
1544 $this->_data['dayPopular'] = $dayPopular;
1545 return $this->_data['dayPopular'];
1548 protected function _registerNamespaces()
1550 $this->_xpath->registerNamespace(
1551 'jungle', 'http://example.com/junglebooks/rss/module/1.0/'
1555 ]]></programlisting>
1558 Let's repeat the last example using a custom Extension to show the
1562 <programlisting language="php"><![CDATA[
1563 if(!Zend_Feed_Reader::isRegistered('JungleBooks')) {
1564 Zend_Feed_Reader::addPrefixPath(
1565 '/path/to/My/FeedReader/Extension', 'My_FeedReader_Extension'
1567 Zend_Feed_Reader::registerExtension('JungleBooks');
1569 $feed = Zend_Feed_Reader::import('http://example.com/junglebooks/rss');
1571 // URI to the information page of the day's most popular book with visitors
1572 $daysPopularBookLink = $feed->getDaysPopularBookLink();
1574 // ISBN for whatever book the first entry in the feed was concerned with
1575 $firstIsbn = $feed->current()->getIsbn();
1576 ]]></programlisting>
1579 Going through these examples, you'll note that we don't register
1580 feed and entry Extensions separately. Extensions within the same
1581 standard may or may not include both a feed and entry class, so
1582 <classname>Zend_Feed_Reader</classname> only requires you to
1583 register the overall parent name, e.g. JungleBooks, DublinCore,
1584 Slash. Internally, it can check at what level Extensions exist
1585 and load them up if found. In our case, we have a full set of
1586 Extensions now: <classname>JungleBooks_Feed</classname> and
1587 <classname>JungleBooks_Entry</classname>.