annotate vendor/zendframework/zend-feed/doc/book/reader.md @ 7:848c88cfe644

More layout
author Chris Cannam
date Fri, 05 Jan 2018 13:59:44 +0000
parents 4c8ae668cc8c
children
rev   line source
Chris@0 1 # Zend\\Feed\\Reader
Chris@0 2
Chris@0 3 `Zend\Feed\Reader` is a component used to consume RSS and Atom feeds of
Chris@0 4 any version, including RDF/RSS 1.0, RSS 2.0, Atom 0.3, and Atom 1.0. The API for
Chris@0 5 retrieving feed data is deliberately simple since `Zend\Feed\Reader` is capable
Chris@0 6 of searching any feed of any type for the information requested through the API.
Chris@0 7 If the typical elements containing this information are not present, it will
Chris@0 8 adapt and fall back on a variety of alternative elements instead. This ability
Chris@0 9 to choose from alternatives removes the need for users to create their own
Chris@0 10 abstraction layer on top of the component to make it useful or have any in-depth
Chris@0 11 knowledge of the underlying standards, current alternatives, and namespaced
Chris@0 12 extensions.
Chris@0 13
Chris@0 14 Internally, the `Zend\Feed\Reader\Reader` class works almost entirely on the
Chris@0 15 basis of making XPath queries against the feed XML's Document Object Model. This
Chris@0 16 singular approach to parsing is consistent, and the component offers a plugin
Chris@0 17 system to add to the Feed and Entry APIs by writing extensions on a similar
Chris@0 18 basis.
Chris@0 19
Chris@0 20 Performance is assisted in three ways. First of all, `Zend\Feed\Reader\Reader`
Chris@0 21 supports caching using [zend-cache](https://github.com/zendframework/zend-cache)
Chris@0 22 to maintain a copy of the original feed XML. This allows you to skip network
Chris@0 23 requests for a feed URI if the cache is valid. Second, the Feed and Entry APIs
Chris@0 24 are backed by an internal cache (non-persistent) so repeat API calls for the
Chris@0 25 same feed will avoid additional DOM or XPath use. Thirdly, importing feeds from
Chris@0 26 a URI can take advantage of HTTP Conditional `GET` requests which allow servers
Chris@0 27 to issue an empty 304 response when the requested feed has not changed since the
Chris@0 28 last time you requested it. In the final case, an zend-cache storage instance
Chris@0 29 will hold the last received feed along with the ETag and Last-Modified header
Chris@0 30 values sent in the HTTP response.
Chris@0 31
Chris@0 32 `Zend\Feed\Reader\Reader` is not capable of constructing feeds, and delegates
Chris@0 33 this responsibility to `Zend\Feed\Writer\Writer`.
Chris@0 34
Chris@0 35 ## Importing Feeds
Chris@0 36
Chris@0 37 Feeds can be imported from a string, file or a URI. Importing from a URI can
Chris@0 38 additionally utilise an HTTP Conditional `GET` request. If importing fails, an
Chris@0 39 exception will be raised. The end result will be an object of type
Chris@0 40 `Zend\Feed\Reader\Feed\AbstractFeed`, the core implementations of which are
Chris@0 41 `Zend\Feed\Reader\Feed\Rss` and `Zend\Feed\Reader\Feed\Atom`. Both objects
Chris@0 42 support multiple (all existing) versions of these broad feed types.
Chris@0 43
Chris@0 44 In the following example, we import an RDF/RSS 1.0 feed and extract some basic
Chris@0 45 information that can be saved to a database or elsewhere.
Chris@0 46
Chris@0 47 ```php
Chris@0 48 $feed = Zend\Feed\Reader\Reader::import('http://www.planet-php.net/rdf/');
Chris@0 49 $data = [
Chris@0 50 'title' => $feed->getTitle(),
Chris@0 51 'link' => $feed->getLink(),
Chris@0 52 'dateModified' => $feed->getDateModified(),
Chris@0 53 'description' => $feed->getDescription(),
Chris@0 54 'language' => $feed->getLanguage(),
Chris@0 55 'entries' => [],
Chris@0 56 ];
Chris@0 57
Chris@0 58 foreach ($feed as $entry) {
Chris@0 59 $edata = [
Chris@0 60 'title' => $entry->getTitle(),
Chris@0 61 'description' => $entry->getDescription(),
Chris@0 62 'dateModified' => $entry->getDateModified(),
Chris@0 63 'authors' => $entry->getAuthors(),
Chris@0 64 'link' => $entry->getLink(),
Chris@0 65 'content' => $entry->getContent(),
Chris@0 66 ];
Chris@0 67 $data['entries'][] = $edata;
Chris@0 68 }
Chris@0 69 ```
Chris@0 70
Chris@0 71 > ## Importing requires an HTTP client
Chris@0 72 >
Chris@0 73 > To import a feed, you will need to have an [HTTP client](zend.feed.http-clients)
Chris@0 74 > available.
Chris@0 75 >
Chris@0 76 > If you are not using zend-http, you will need to inject `Reader` with the HTTP
Chris@0 77 > client. See the [section on providing a client to Reader](http-clients.md#providing-a-client-to-reader).
Chris@0 78
Chris@0 79 The example above demonstrates `Zend\Feed\Reader\Reader`'s API, and it also
Chris@0 80 demonstrates some of its internal operation. In reality, the RDF feed selected
Chris@0 81 does not have any native date or author elements; however it does utilise the
Chris@0 82 Dublin Core 1.1 module which offers namespaced creator and date elements.
Chris@0 83 `Zend\Feed\Reader\Reader` falls back on these and similar options if no relevant
Chris@0 84 native elements exist. If it absolutely cannot find an alternative it will
Chris@0 85 return `NULL`, indicating the information could not be found in the feed. You
Chris@0 86 should note that classes implementing `Zend\Feed\Reader\Feed\AbstractFeed` also
Chris@0 87 implement the SPL `Iterator` and `Countable` interfaces.
Chris@0 88
Chris@0 89 Feeds can also be imported from strings or files.
Chris@0 90
Chris@0 91 ```php
Chris@0 92 // from a URI
Chris@0 93 $feed = Zend\Feed\Reader\Reader::import('http://www.planet-php.net/rdf/');
Chris@0 94
Chris@0 95 // from a String
Chris@0 96 $feed = Zend\Feed\Reader\Reader::importString($feedXmlString);
Chris@0 97
Chris@0 98 // from a file
Chris@0 99 $feed = Zend\Feed\Reader\Reader::importFile('./feed.xml');
Chris@0 100 ```
Chris@0 101
Chris@0 102 ## Retrieving Underlying Feed and Entry Sources
Chris@0 103
Chris@0 104 `Zend\Feed\Reader\Reader` does its best not to stick you in a narrow confine. If
Chris@0 105 you need to work on a feed outside of `Zend\Feed\Reader\Reader`, you can extract
Chris@0 106 the base DOMDocument or DOMElement objects from any class, or even an XML
Chris@0 107 string containing these. Also provided are methods to extract the current
Chris@0 108 DOMXPath object (with all core and extension namespaces registered) and the
Chris@0 109 correct prefix used in all XPath queries for the current feed or entry. The
Chris@0 110 basic methods to use (on any object) are `saveXml()`, `getDomDocument()`,
Chris@0 111 `getElement()`, `getXpath()` and `getXpathPrefix()`. These will let you break
Chris@0 112 free of `Zend\Feed\Reader` and do whatever else you want.
Chris@0 113
Chris@0 114 - `saveXml()` returns an XML string containing only the element representing the
Chris@0 115 current object.
Chris@0 116 - `getDomDocument()` returns the DOMDocument object representing the entire feed
Chris@0 117 (even if called from an entry object).
Chris@0 118 - `getElement()` returns the DOMElement of the current object (i.e. the feed or
Chris@0 119 current entry).
Chris@0 120 - `getXpath()` returns the DOMXPath object for the current feed (even if called
Chris@0 121 from an entry object) with the namespaces of the current feed type and all
Chris@0 122 loaded extensions pre-registered.
Chris@0 123 - `getXpathPrefix()` returns the query prefix for the current object (i.e. the
Chris@0 124 feed or current entry) which includes the correct XPath query path for that
Chris@0 125 specific feed or entry.
Chris@0 126
Chris@0 127 Let's look at an example where a feed might include an RSS extension not
Chris@0 128 supported by `Zend\Feed\Reader\Reader` out of the box. Notably, you could write
Chris@0 129 and register an extension (covered later) to do this, but that's not always
Chris@0 130 warranted for a quick check. You must register any new namespaces on the
Chris@0 131 DOMXPath object before use unless they are registered by `Zend\Feed\Reader` or
Chris@0 132 an extension beforehand.
Chris@0 133
Chris@0 134 ```php
Chris@0 135 $feed = Zend\Feed\Reader\Reader::import('http://www.planet-php.net/rdf/');
Chris@0 136 $xpathPrefix = $feed->getXpathPrefix();
Chris@0 137 $xpath = $feed->getXpath();
Chris@0 138 $xpath->registerNamespace('admin', 'http://webns.net/mvcb/');
Chris@0 139 $reportErrorsTo = $xpath->evaluate(
Chris@0 140 'string(' . $xpathPrefix . '/admin:errorReportsTo)'
Chris@0 141 );
Chris@0 142 ```
Chris@0 143
Chris@0 144 > ### Do not register duplicate namespaces
Chris@0 145 >
Chris@0 146 > If you register an already registered namespace with a different prefix name
Chris@0 147 > to that used internally by `Zend\Feed\Reader\Reader`, it will break the
Chris@0 148 > internal operation of this component.
Chris@0 149
Chris@0 150 ## Cache Support and Intelligent Requests
Chris@0 151
Chris@0 152 ### Adding Cache Support to Zend\\Feed\\Reader\\Reader
Chris@0 153
Chris@0 154 `Zend\Feed\Reader\Reader` supports using a
Chris@0 155 [zend-cache](https://github.com/zendframework/zend-cache) storage instance to
Chris@0 156 cache feeds (as XML) to avoid unnecessary network requests. To add a cache,
Chris@0 157 create and configure your cache instance, and then tell
Chris@0 158 `Zend\Feed\Reader\Reader` to use it. The cache key used is
Chris@0 159 "`Zend\Feed\Reader\\`" followed by the MD5 hash of the feed's URI.
Chris@0 160
Chris@0 161 ```php
Chris@0 162 $cache = Zend\Cache\StorageFactory::adapterFactory('Memory');
Chris@0 163 Zend\Feed\Reader\Reader::setCache($cache);
Chris@0 164 ```
Chris@0 165
Chris@0 166 ### HTTP Conditional GET Support
Chris@0 167
Chris@0 168 The big question often asked when importing a feed frequently is if it has even
Chris@0 169 changed. With a cache enabled, you can add HTTP Conditional `GET` support to
Chris@0 170 your arsenal to answer that question.
Chris@0 171
Chris@0 172 Using this method, you can request feeds from URIs and include their last known
Chris@0 173 ETag and Last-Modified response header values with the request (using the
Chris@0 174 If-None-Match and If-Modified-Since headers). If the feed on the server remains
Chris@0 175 unchanged, you should receive a 304 response which tells
Chris@0 176 `Zend\Feed\Reader\Reader` to use the cached version. If a full feed is sent in a
Chris@0 177 response with a status code of 200, this means the feed has changed and
Chris@0 178 `Zend\Feed\Reader\Reader` will parse the new version and save it to the cache.
Chris@0 179 It will also cache the new ETag and Last-Modified header values for future use.
Chris@0 180
Chris@0 181 > #### Conditional GET requires a HeaderAwareClientInterface
Chris@0 182 >
Chris@0 183 > Conditional GET support only works for `Zend\Feed\Reader\Http\HeaderAwareClientInterface`
Chris@0 184 > client implementations, as it requires the ability to send HTTP headers.
Chris@0 185
Chris@0 186 These "conditional" requests are not guaranteed to be supported by the server
Chris@0 187 you request a *URI* of, but can be attempted regardless. Most common feed
Chris@0 188 sources like blogs should however have this supported. To enable conditional
Chris@0 189 requests, you will need to provide a cache to `Zend\Feed\Reader\Reader`.
Chris@0 190
Chris@0 191 ```php
Chris@0 192 $cache = Zend\Cache\StorageFactory::adapterFactory('Memory');
Chris@0 193
Chris@0 194 Zend\Feed\Reader\Reader::setCache($cache);
Chris@0 195 Zend\Feed\Reader\Reader::useHttpConditionalGet();
Chris@0 196
Chris@0 197 $feed = Zend\Feed\Reader\Reader::import('http://www.planet-php.net/rdf/');
Chris@0 198 ```
Chris@0 199
Chris@0 200 In the example above, with HTTP Conditional `GET` requests enabled, the response
Chris@0 201 header values for ETag and Last-Modified will be cached along with the feed. For
Chris@0 202 the the cache's lifetime, feeds will only be updated on the cache if a non-304
Chris@0 203 response is received containing a valid RSS or Atom XML document.
Chris@0 204
Chris@0 205 If you intend on managing request headers from outside
Chris@0 206 `Zend\Feed\Reader\Reader`, you can set the relevant If-None-Matches and
Chris@0 207 If-Modified-Since request headers via the URI import method.
Chris@0 208
Chris@0 209 ```php
Chris@0 210 $lastEtagReceived = '5e6cefe7df5a7e95c8b1ba1a2ccaff3d';
Chris@0 211 $lastModifiedDateReceived = 'Wed, 08 Jul 2009 13:37:22 GMT';
Chris@0 212 $feed = Zend\Feed\Reader\Reader::import(
Chris@0 213 $uri, $lastEtagReceived, $lastModifiedDateReceived
Chris@0 214 );
Chris@0 215 ```
Chris@0 216
Chris@0 217 ## Locating Feed URIs from Websites
Chris@0 218
Chris@0 219 These days, many websites are aware that the location of their XML feeds is not
Chris@0 220 always obvious. A small RDF, RSS, or Atom graphic helps when the user is reading
Chris@0 221 the page, but what about when a machine visits trying to identify where your
Chris@0 222 feeds are located? To assist in this, websites may point to their feeds using
Chris@0 223 `<link>` tags in the `<head>` section of their HTML. To take advantage
Chris@0 224 of this, you can use `Zend\Feed\Reader\Reader` to locate these feeds using the
Chris@0 225 static `findFeedLinks()` method.
Chris@0 226
Chris@0 227 This method calls any URI and searches for the location of RSS, RDF, and Atom
Chris@0 228 feeds assuming, the website's HTML contains the relevant links. It then returns
Chris@0 229 a value object where you can check for the existence of a RSS, RDF or Atom feed
Chris@0 230 URI.
Chris@0 231
Chris@0 232 The returned object is an `ArrayObject` subclass called
Chris@0 233 `Zend\Feed\Reader\FeedSet`, so you can cast it to an array or iterate over it to
Chris@0 234 access all the detected links. However, as a simple shortcut, you can just grab
Chris@0 235 the first RSS, RDF, or Atom link using its public properties as in the example
Chris@0 236 below. Otherwise, each element of the `ArrayObject` is a simple array with the
Chris@0 237 keys `type` and `uri` where the type is one of "rdf", "rss", or "atom".
Chris@0 238
Chris@0 239 ```php
Chris@0 240 $links = Zend\Feed\Reader\Reader::findFeedLinks('http://www.planet-php.net');
Chris@0 241
Chris@0 242 if (isset($links->rdf)) {
Chris@0 243 echo $links->rdf, "\n"; // http://www.planet-php.org/rdf/
Chris@0 244 }
Chris@0 245 if (isset($links->rss)) {
Chris@0 246 echo $links->rss, "\n"; // http://www.planet-php.org/rss/
Chris@0 247 }
Chris@0 248 if (isset($links->atom)) {
Chris@0 249 echo $links->atom, "\n"; // http://www.planet-php.org/atom/
Chris@0 250 }
Chris@0 251 ```
Chris@0 252
Chris@0 253 Based on these links, you can then import from whichever source you wish in the usual manner.
Chris@0 254
Chris@0 255 > ### Finding feed links requires an HTTP client
Chris@0 256 >
Chris@0 257 > To find feed links, you will need to have an [HTTP client](zend.feed.http-clients)
Chris@0 258 > available.
Chris@0 259 >
Chris@0 260 > If you are not using zend-http, you will need to inject `Reader` with the HTTP
Chris@0 261 > client. See the [section on providing a client to Reader](http-clients.md#providing-a-client-to-reader).
Chris@0 262
Chris@0 263 This quick method only gives you one link for each feed type, but websites may
Chris@0 264 indicate many links of any type. Perhaps it's a news site with a RSS feed for
Chris@0 265 each news category. You can iterate over all links using the ArrayObject's
Chris@0 266 iterator.
Chris@0 267
Chris@0 268 ```php
Chris@0 269 $links = Zend\Feed\Reader::findFeedLinks('http://www.planet-php.net');
Chris@0 270
Chris@0 271 foreach ($links as $link) {
Chris@0 272 echo $link['href'], "\n";
Chris@0 273 }
Chris@0 274 ```
Chris@0 275
Chris@0 276 ## Attribute Collections
Chris@0 277
Chris@0 278 In an attempt to simplify return types, return types from the various feed and
Chris@0 279 entry level methods may include an object of type
Chris@0 280 `Zend\Feed\Reader\Collection\AbstractCollection`. Despite the special class name
Chris@0 281 which I'll explain below, this is just a simple subclass of SPL's `ArrayObject`.
Chris@0 282
Chris@0 283 The main purpose here is to allow the presentation of as much data as possible
Chris@0 284 from the requested elements, while still allowing access to the most relevant
Chris@0 285 data as a simple array. This also enforces a standard approach to returning such
Chris@0 286 data which previously may have wandered between arrays and objects.
Chris@0 287
Chris@0 288 The new class type acts identically to `ArrayObject` with the sole addition
Chris@0 289 being a new method `getValues()` which returns a simple flat array containing
Chris@0 290 the most relevant information.
Chris@0 291
Chris@0 292 A simple example of this is `Zend\Feed\Reader\Reader\FeedInterface::getCategories()`.
Chris@0 293 When used with any RSS or Atom feed, this method will return category data as a
Chris@0 294 container object called `Zend\Feed\Reader\Collection\Category`. The container
Chris@0 295 object will contain, per category, three fields of data: term, scheme, and label.
Chris@0 296 The "term" is the basic category name, often machine readable (i.e. plays nice
Chris@0 297 with URIs). The scheme represents a categorisation scheme (usually a URI
Chris@0 298 identifier) also known as a "domain" in RSS 2.0. The "label" is a human readable
Chris@0 299 category name which supports HTML entities. In RSS 2.0, there is no label
Chris@0 300 attribute so it is always set to the same value as the term for convenience.
Chris@0 301
Chris@0 302 To access category labels by themselves in a simple value array, you might
Chris@0 303 commit to something like:
Chris@0 304
Chris@0 305 ```php
Chris@0 306 $feed = Zend\Feed\Reader\Reader::import('http://www.example.com/atom.xml');
Chris@0 307 $categories = $feed->getCategories();
Chris@0 308 $labels = [];
Chris@0 309 foreach ($categories as $cat) {
Chris@0 310 $labels[] = $cat['label']
Chris@0 311 }
Chris@0 312 ```
Chris@0 313
Chris@0 314 It's a contrived example, but the point is that the labels are tied up with
Chris@0 315 other information.
Chris@0 316
Chris@0 317 However, the container class allows you to access the "most relevant" data as a
Chris@0 318 simple array using the `getValues()` method. The concept of "most relevant" is
Chris@0 319 obviously a judgement call. For categories it means the category labels (not the
Chris@0 320 terms or schemes) while for authors it would be the authors' names (not their
Chris@0 321 email addresses or URIs). The simple array is flat (just values) and passed
Chris@0 322 through `array_unique()` to remove duplication.
Chris@0 323
Chris@0 324 ```php
Chris@0 325 $feed = Zend\Feed\Reader\Reader::import('http://www.example.com/atom.xml');
Chris@0 326 $categories = $feed->getCategories();
Chris@0 327 $labels = $categories->getValues();
Chris@0 328 ```
Chris@0 329
Chris@0 330 The above example shows how to extract only labels and nothing else thus giving
Chris@0 331 simple access to the category labels without any additional work to extract that
Chris@0 332 data by itself.
Chris@0 333
Chris@0 334 ## Retrieving Feed Information
Chris@0 335
Chris@0 336 Retrieving information from a feed (we'll cover entries and items in the next
Chris@0 337 section though they follow identical principals) uses a clearly defined API
Chris@0 338 which is exactly the same regardless of whether the feed in question is RSS,
Chris@0 339 RDF, or Atom. The same goes for sub-versions of these standards and we've tested
Chris@0 340 every single RSS and Atom version. While the underlying feed XML can differ
Chris@0 341 substantially in terms of the tags and elements they present, they nonetheless
Chris@0 342 are all trying to convey similar information and to reflect this all the
Chris@0 343 differences and wrangling over alternative tags are handled internally by
Chris@0 344 `Zend\Feed\Reader\Reader` presenting you with an identical interface for each.
Chris@0 345 Ideally, you should not have to care whether a feed is RSS or Atom so long as
Chris@0 346 you can extract the information you want.
Chris@0 347
Chris@0 348 > ### RSS feeds vary widely
Chris@0 349 >
Chris@0 350 > While determining common ground between feed types is itself complex, it
Chris@0 351 > should be noted that *RSS* in particular is a constantly disputed
Chris@0 352 > "specification". This has its roots in the original RSS 2.0 document, which
Chris@0 353 > contains ambiguities and does not detail the correct treatment of all
Chris@0 354 > elements. As a result, this component rigorously applies the RSS 2.0.11
Chris@0 355 > Specification published by the RSS Advisory Board and its accompanying RSS
Chris@0 356 > Best Practices Profile. No other interpretation of RSS
Chris@0 357 > 2.0 will be supported, though exceptions may be allowed where it does not
Chris@0 358 > directly prevent the application of the two documents mentioned above.
Chris@0 359
Chris@0 360 Of course, we don't live in an ideal world, so there may be times the API just
Chris@0 361 does not cover what you're looking for. To assist you, `Zend\Feed\Reader\Reader`
Chris@0 362 offers a plugin system which allows you to write extensions to expand the core
Chris@0 363 API and cover any additional data you are trying to extract from feeds. If
Chris@0 364 writing another extension is too much trouble, you can simply grab the
Chris@0 365 underlying DOM or XPath objects and do it by hand in your application. Of
Chris@0 366 course, we really do encourage writing an extension simply to make it more
Chris@0 367 portable and reusable, and useful extensions may be proposed to the component
Chris@0 368 for formal addition.
Chris@0 369
Chris@0 370 Below is a summary of the Core API for feeds. You should note it comprises not
Chris@0 371 only the basic RSS and Atom standards, but also accounts for a number of
Chris@0 372 included extensions bundled with `Zend\Feed\Reader\Reader`. The naming of these
Chris@0 373 extension sourced methods remain fairly generic; all Extension methods operate
Chris@0 374 at the same level as the Core API though we do allow you to retrieve any
Chris@0 375 specific extension object separately if required.
Chris@0 376
Chris@0 377 ### Feed Level API Methods
Chris@0 378
Chris@0 379 Method | Description
Chris@0 380 ------ | -----------
Chris@0 381 `getId()` | Returns a unique ID associated with this feed
Chris@0 382 `getTitle()` | Returns the title of the feed
Chris@0 383 `getDescription()` | Returns the text description of the feed.
Chris@0 384 `getLink()` | Returns a URI to the HTML website containing the same or similar information as this feed (i.e. if the feed is from a blog, it should provide the blog's URI where the HTML version of the entries can be read).
Chris@0 385 `getFeedLink()` | Returns the URI of this feed, which may be the same as the URI used to import the feed. There are important cases where the feed link may differ because the source URI is being updated and is intended to be removed in the future.
Chris@0 386 `getAuthors()` | Returns an object of type `Zend\Feed\Reader\Collection\Author` which is an `ArrayObject` whose elements are each simple arrays containing any combination of the keys "name", "email" and "uri". Where irrelevant to the source data, some of these keys may be omitted.
Chris@0 387 `getAuthor(integer $index = 0)` | Returns either the first author known, or with the optional $index parameter any specific index on the array of authors as described above (returning `NULL` if an invalid index).
Chris@0 388 `getDateCreated()` | Returns the date on which this feed was created. Generally only applicable to Atom, where it represents the date the resource described by an Atom 1.0 document was created. The returned date will be a `DateTime` object.
Chris@0 389 `getDateModified()` | Returns the date on which this feed was last modified. The returned date will be a `DateTime` object.
Chris@0 390 `getLastBuildDate()` | Returns the date on which this feed was last built. The returned date will be a `DateTime` object. This is only supported by RSS; Atom feeds will always return `NULL`.
Chris@0 391 `getLanguage()` | Returns the language of the feed (if defined) or simply the language noted in the XML document.
Chris@0 392 `getGenerator()` | Returns the generator of the feed, e.g. the software which generated it. This may differ between RSS and Atom since Atom defines a different notation.
Chris@0 393 `getCopyright()` | Returns any copyright notice associated with the feed.
Chris@0 394 `getHubs()` | Returns an array of all Hub Server URI endpoints which are advertised by the feed for use with the Pubsubhubbub Protocol, allowing subscriptions to the feed for real-time updates.
Chris@0 395 `getCategories()` | Returns a `Zend\Feed\Reader\Collection\Category` object containing the details of any categories associated with the overall feed. The supported fields include "term" (the machine readable category name), "scheme" (the categorisation scheme and domain for this category), and "label" (a HTML decoded human readable category name). Where any of the three fields are absent from the field, they are either set to the closest available alternative or, in the case of "scheme", set to `NULL`.
Chris@0 396 `getImage()` | Returns an array containing data relating to any feed image or logo, or `NULL` if no image found. The resulting array may contain the following keys: uri, link, title, description, height, and width. Atom logos only contain a URI so the remaining metadata is drawn from RSS feeds only.
Chris@0 397
Chris@0 398 Given the variety of feeds in the wild, some of these methods will undoubtedly
Chris@0 399 return `NULL` indicating the relevant information couldn't be located. Where
Chris@0 400 possible, `Zend\Feed\Reader\Reader` will fall back on alternative elements
Chris@0 401 during its search. For example, searching an RSS feed for a modification date is
Chris@0 402 more complicated than it looks. RSS 2.0 feeds should include a `<lastBuildDate>`
Chris@0 403 tag and/or a `<pubDate>` element. But what if it doesn't? Maybe this is an RSS
Chris@0 404 1.0 feed? Perhaps it instead has an `<atom:updated>` element with identical
Chris@0 405 information (Atom may be used to supplement RSS syntax)? Failing that, we
Chris@0 406 could simply look at the entries, pick the most recent, and use its `<pubDate>`
Chris@0 407 element. Assuming it exists, that is. Many feeds also use Dublin Core 1.0 or 1.1
Chris@0 408 `<dc:date>` elements for feeds and entries. Or we could find Atom lurking again.
Chris@0 409
Chris@0 410 The point is, `Zend\Feed\Reader\Reader` was designed to know this. When you ask
Chris@0 411 for the modification date (or anything else), it will run off and search for all
Chris@0 412 these alternatives until it either gives up and returns `NULL`, or finds an
Chris@0 413 alternative that should have the right answer.
Chris@0 414
Chris@0 415 In addition to the above methods, all feed objects implement methods for
Chris@0 416 retrieving the DOM and XPath objects for the current feeds as described
Chris@0 417 earlier. Feed objects also implement the SPL Iterator and Countable
Chris@0 418 interfaces. The extended API is summarised below.
Chris@0 419
Chris@0 420 ### Extended Feed API Methods
Chris@0 421
Chris@0 422 Method | Description
Chris@0 423 ------ | -----------
Chris@0 424 `getDomDocument()` | Returns the parent DOMDocument object for the entire source XML document.
Chris@0 425 `getElement()` | Returns the current feed level DOMElement object.
Chris@0 426 `saveXml()` | Returns a string containing an XML document of the entire feed element (this is not the original document, but a rebuilt version).
Chris@0 427 `getXpath()` | Returns the DOMXPath object used internally to run queries on the DOMDocument object (this includes core and extension namespaces pre-registered).
Chris@0 428 `getXpathPrefix()` | Returns the valid DOM path prefix prepended to all XPath queries matching the feed being queried.
Chris@0 429 `getEncoding()` | Returns the encoding of the source XML document (note: this cannot account for errors such as the server sending documents in a different encoding). Where not defined, the default UTF-8 encoding of Unicode is applied.
Chris@0 430 `count()` | Returns a count of the entries or items this feed contains (implements SPL `Countable` interface)
Chris@0 431 `current()` | Returns either the current entry (using the current index from `key()`).
Chris@0 432 `key()` | Returns the current entry index.
Chris@0 433 `next()` | Increments the entry index value by one.
Chris@0 434 `rewind()` | Resets the entry index to 0.
Chris@0 435 `valid()` | Checks that the current entry index is valid, i.e. it does not fall below 0 and does not exceed the number of entries existing.
Chris@0 436 `getExtensions()` | Returns an array of all extension objects loaded for the current feed (note: both feed-level and entry-level extensions exist, and only feed-level extensions are returned here). The array keys are of the form `{ExtensionName}_Feed`.
Chris@0 437 `getExtension(string $name)` | Returns an extension object for the feed registered under the provided name. This allows more fine-grained access to extensions which may otherwise be hidden within the implementation of the standard API methods.
Chris@0 438 `getType()` | Returns a static class constant (e.g. `Zend\Feed\Reader\Reader::TYPE_ATOM_03`, i.e. "Atom 0.3"), indicating exactly what kind of feed is being consumed.
Chris@0 439
Chris@0 440 ## Retrieving Entry/Item Information
Chris@0 441
Chris@0 442 Retrieving information for specific entries or items (depending on whether you
Chris@0 443 speak Atom or RSS) is identical to feed level data. Accessing entries is
Chris@0 444 simply a matter of iterating over a feed object or using the SPL `Iterator`
Chris@0 445 interface feed objects implement, and calling the appropriate method on each.
Chris@0 446
Chris@0 447 ### Entry API Methods
Chris@0 448
Chris@0 449 Method | Description
Chris@0 450 ------ | -----------
Chris@0 451 `getId()` | Returns a unique ID for the current entry.
Chris@0 452 `getTitle()` | Returns the title of the current entry.
Chris@0 453 `getDescription()` | Returns a description of the current entry.
Chris@0 454 `getLink()` | Returns a URI to the HTML version of the current entry.
Chris@0 455 `getPermaLink()` | Returns the permanent link to the current entry. In most cases, this is the same as using `getLink()`.
Chris@0 456 `getAuthors()` | Returns an object of type `Zend\Feed\Reader\Collection\Author`, which is an `ArrayObject` whose elements are each simple arrays containing any combination of the keys "name", "email" and "uri". Where irrelevant to the source data, some of these keys may be omitted.
Chris@0 457 `getAuthor(integer $index = 0)` | Returns either the first author known, or, with the optional `$index` parameter, any specific index on the array of Authors as described above (returning `NULL` if an invalid index).
Chris@0 458 `getDateCreated()` | Returns the date on which the current entry was created. Generally only applicable to Atom where it represents the date the resource described by an Atom 1.0 document was created.
Chris@0 459 `getDateModified()` | Returns the date on which the current entry was last modified.
Chris@0 460 `getContent()` | Returns the content of the current entry (this has any entities reversed if possible, assuming the content type is HTML). The description is returned if a separate content element does not exist.
Chris@0 461 `getEnclosure()` | Returns an array containing the value of all attributes from a multi-media `<enclosure>` element including as array keys: url, length, type. In accordance with the RSS Best Practices Profile of the RSS Advisory Board, no support is offers for multiple enclosures since such support forms no part of the RSS specification.
Chris@0 462 `getCommentCount()` | Returns the number of comments made on this entry at the time the feed was last generated.
Chris@0 463 `getCommentLink()` | Returns a URI pointing to the HTML page where comments can be made on this entry.
Chris@0 464 `getCommentFeedLink([string $type = ‘atom'|'rss'])` | Returns a URI pointing to a feed of the provided type containing all comments for this entry (type defaults to Atom/RSS depending on current feed type).
Chris@0 465 `getCategories()` | Returns a `Zend\Feed\Reader\Collection\Category` object containing the details of any categories associated with the entry. The supported fields include "term" (the machine readable category name), "scheme" (the categorisation scheme and domain for this category), and "label" (an HTML-decoded human readable category name). Where any of the three fields are absent from the field, they are either set to the closest available alternative or, in the case of "scheme", set to `NULL`.
Chris@0 466
Chris@0 467 The extended API for entries is identical to that for feeds with the exception
Chris@0 468 of the `Iterator` methods, which are not needed here.
Chris@0 469
Chris@0 470 > ### Modified vs Created dates
Chris@0 471 >
Chris@0 472 > There is often confusion over the concepts of *modified* and *created* dates.
Chris@0 473 > In Atom, these are two clearly defined concepts (so knock yourself out) but in
Chris@0 474 > RSS they are vague. RSS 2.0 defines a single `<pubDate>` element which
Chris@0 475 > typically refers to the date this entry was published, i.e. a creation date of
Chris@0 476 > sorts. This is not always the case, and it may change with updates or not. As a
Chris@0 477 > result, if you really want to check whether an entry has changed, don't rely on
Chris@0 478 > the results of `getDateModified()`. Instead, consider tracking the MD5 hash of
Chris@0 479 > three other elements concatenated, e.g. using `getTitle()`, `getDescription()`,
Chris@0 480 > and `getContent()`. If the entry was truly updated, this hash computation will
Chris@0 481 > give a different result than previously saved hashes for the same entry. This
Chris@0 482 > is obviously content oriented, and will not assist in detecting changes to
Chris@0 483 > other relevant elements. Atom feeds should not require such steps.
Chris@0 484
Chris@0 485 > Further muddying the waters, dates in feeds may follow different standards.
Chris@0 486 > Atom and Dublin Core dates should follow ISO 8601, and RSS dates should
Chris@0 487 > follow RFC 822 or RFC 2822 (which is also common). Date methods will throw an
Chris@0 488 > exception if `DateTime` cannot load the date string using one of the above
Chris@0 489 > standards, or the PHP recognised possibilities for RSS dates.
Chris@0 490
Chris@0 491 > ### Validation
Chris@0 492 >
Chris@0 493 > The values returned from these methods are not validated. This means users
Chris@0 494 > must perform validation on all retrieved data including the filtering of any
Chris@0 495 > HTML such as from `getContent()` before it is output from your application.
Chris@0 496 > Remember that most feeds come from external sources, and therefore the default
Chris@0 497 > assumption should be that they cannot be trusted.
Chris@0 498
Chris@0 499 ### Extended Entry Level API Methods
Chris@0 500
Chris@0 501 Method | Description
Chris@0 502 ------ | -----------
Chris@0 503 `getDomDocument()` | Returns the parent DOMDocument object for the entire feed (not just the current entry).
Chris@0 504 `getElement()` | Returns the current entry level DOMElement object.
Chris@0 505 `getXpath()` | Returns the DOMXPath object used internally to run queries on the DOMDocument object (this includes core and extension namespaces pre-registered).
Chris@0 506 `getXpathPrefix()` | Returns the valid DOM path prefix prepended to all XPath queries matching the entry being queried.
Chris@0 507 `getEncoding()` | Returns the encoding of the source XML document (note: this cannot account for errors such as the server sending documents in a different encoding). The default encoding applied in the absence of any other is the UTF-8 encoding of Unicode.
Chris@0 508 `getExtensions()` | Returns an array of all extension objects loaded for the current entry (note: both feed-level and entry-level extensions exist, and only entry-level extensions are returned here). The array keys are in the form `{ExtensionName}Entry`.
Chris@0 509 `getExtension(string $name)` | Returns an extension object for the entry registered under the provided name. This allows more fine-grained access to extensions which may otherwise be hidden within the implementation of the standard API methods.
Chris@0 510 `getType()` | Returns a static class constant (e.g. `Zend\Feed\Reader\Reader::TYPE_ATOM_03`, i.e. "Atom 0.3") indicating exactly what kind of feed is being consumed.
Chris@0 511
Chris@0 512 ## Extending Feed and Entry APIs
Chris@0 513
Chris@0 514 Extending `Zend\Feed\Reader\Reader` allows you to add methods at both the feed
Chris@0 515 and entry level which cover the retrieval of information not already supported
Chris@0 516 by `Zend\Feed\Reader\Reader`. Given the number of RSS and Atom extensions that
Chris@0 517 exist, this is a good thing, since `Zend\Feed\Reader\Reader` couldn't possibly
Chris@0 518 add everything.
Chris@0 519
Chris@0 520 There are two types of extensions possible, those which retrieve information
Chris@0 521 from elements which are immediate children of the root element (e.g.
Chris@0 522 `<channel>` for RSS or `<feed>` for Atom), and those who retrieve information
Chris@0 523 from child elements of an entry (e.g. `<item>` for RSS or `<entry>` for Atom).
Chris@0 524 On the filesystem, these are grouped as classes within a namespace based on the
Chris@0 525 extension standard's name. For example, internally we have
Chris@0 526 `Zend\Feed\Reader\Extension\DublinCore\Feed` and
Chris@0 527 `Zend\Feed\Reader\Extension\DublinCore\Entry` classes which are two extensions
Chris@0 528 implementing Dublin Core 1.0 and 1.1 support.
Chris@0 529
Chris@0 530 Extensions are loaded into `Zend\Feed\Reader\Reader` using an "extension
Chris@0 531 manager". Extension managers must implement `Zend\Feed\Reader\ExtensionManagerInterface`.
Chris@0 532 Three implementations exist:
Chris@0 533
Chris@0 534 - `Zend\Feed\Reader\StandaloneExtensionManager` is a hard-coded implementation
Chris@0 535 seeded with all feed and entry implementations. You can extend it to add
Chris@0 536 extensions, though it's likely easier to copy and paste it, adding your
Chris@0 537 changes.
Chris@0 538 - `Zend\Feed\Reader\ExtensionPluginManager` is a `Zend\ServiceManager\AbstractPluginManager`
Chris@0 539 implementation, `Zend\Feed\Reader\ExtensionManager`; as such, you can extend
Chris@0 540 it to add more extensions, use a `Zend\ServiceManager\ConfigInterface` instance
Chris@0 541 to inject it with more extensions, or use its public API for adding services
Chris@0 542 (e.g., `setService()`, `setFactory()`, etc.). This implementation *does not*
Chris@0 543 implement `ExtensionManagerInterface`, and must be used with `ExtensionManager`.
Chris@0 544 - `Zend\Feed\Reader\ExtensionManager` exists for legacy purposes; prior to 2.3,
Chris@0 545 this was an `AbstractPluginManager` implementation, and the only provided
Chris@0 546 extension manager. It now implements `ExtensionManagerInterface`, and acts as
Chris@0 547 a decorator for `ExtensionPluginManager`.
Chris@0 548
Chris@0 549 By default, `Zend\Feed\Reader\Reader` composes a `StandaloneExtensionManager`. You
Chris@0 550 can inject an alternate implementation using `Reader::setExtensionManager()`:
Chris@0 551
Chris@0 552 ```php
Chris@0 553 $extensions = new Zend\Feed\Reader\ExtensionPluginManager();
Chris@0 554 Zend\Feed\Reader\Reader::setExtensionManager(
Chris@0 555 new ExtensionManager($extensions)
Chris@0 556 );
Chris@0 557 ```
Chris@0 558
Chris@0 559 The shipped implementations all provide the default extensions (so-called
Chris@0 560 "Core Extensions") used internally by `Zend\Feed\Reader\Reader`. These
Chris@0 561 include:
Chris@0 562
Chris@0 563 Extension | Description
Chris@0 564 --------- | -----------
Chris@0 565 DublinCore (Feed and Entry) | Implements support for Dublin Core Metadata Element Set 1.0 and 1.1.
Chris@0 566 Content (Entry only) | Implements support for Content 1.0.
Chris@0 567 Atom (Feed and Entry) | Implements support for Atom 0.3 and Atom 1.0.
Chris@0 568 Slash | Implements support for the Slash RSS 1.0 module.
Chris@0 569 WellFormedWeb | Implements support for the Well Formed Web CommentAPI 1.0.
Chris@0 570 Thread | Implements support for Atom Threading Extensions as described in RFC 4685.
Chris@0 571 Podcast | Implements support for the Podcast 1.0 DTD from Apple.
Chris@0 572
Chris@0 573 The core extensions are somewhat special since they are extremely common and
Chris@0 574 multi-faceted. For example, we have a core extension for Atom. Atom is
Chris@0 575 implemented as an extension (not just a base class) because it doubles as a
Chris@0 576 valid RSS module; you can insert Atom elements into RSS feeds. I've even seen
Chris@0 577 RDF feeds which use a lot of Atom in place of more common extensions like
Chris@0 578 Dublin Core.
Chris@0 579
Chris@0 580 The following is a list of non-Core extensions that are offered, but not registered
Chris@0 581 by default. If you want to use them, you'll need to
Chris@0 582 tell `Zend\Feed\Reader\Reader` to load them in advance of importing a feed.
Chris@0 583 Additional non-Core extensions will be included in future iterations of the
Chris@0 584 component.
Chris@0 585
Chris@0 586 Extension | Description
Chris@0 587 --------- | -----------
Chris@0 588 Syndication | Implements Syndication 1.0 support for RSS feeds.
Chris@0 589 CreativeCommons | An RSS module that adds an element at the `<channel>` or `<item>` level that specifies which Creative Commons license applies.
Chris@0 590
Chris@0 591 `Zend\Feed\Reader\Reader` requires you to explicitly register non-Core
Chris@0 592 extensions in order to expose their API to feed and entry objects. Below, we
Chris@0 593 register the optional Syndication extension, and discover that it can be
Chris@0 594 directly called from the entry API without any effort. (Note that
Chris@0 595 extension names are case sensitive and use camelCasing for multiple terms.)
Chris@0 596
Chris@0 597 ```php
Chris@0 598 use Zend\Feed\Reader\Reader;
Chris@0 599
Chris@0 600 Reader::registerExtension('Syndication');
Chris@0 601 $feed = Reader::import('http://rss.slashdot.org/Slashdot/slashdot');
Chris@0 602 $updatePeriod = $feed->getUpdatePeriod();
Chris@0 603 ```
Chris@0 604
Chris@0 605 In the simple example above, we checked how frequently a feed is being updated
Chris@0 606 using the `getUpdatePeriod()` method. Since it's not part of
Chris@0 607 `Zend\Feed\Reader\Reader`'s core API, it could only be a method supported by
Chris@0 608 the newly registered Syndication extension.
Chris@0 609
Chris@0 610 As you can also notice, methods provided by extensions are accessible from the
Chris@0 611 main API using method overloading. As an alternative, you can also directly
Chris@0 612 access any extension object for a similar result as seen below.
Chris@0 613
Chris@0 614 ```php
Chris@0 615 use Zend\Feed\Reader\Reader;
Chris@0 616
Chris@0 617 Reader::registerExtension('Syndication');
Chris@0 618 $feed = Reader::import('http://rss.slashdot.org/Slashdot/slashdot');
Chris@0 619 $syndication = $feed->getExtension('Syndication');
Chris@0 620 $updatePeriod = $syndication->getUpdatePeriod();
Chris@0 621 ```
Chris@0 622
Chris@0 623 ### Writing Zend\\Feed\\Reader Extensions
Chris@0 624
Chris@0 625 Inevitably, there will be times when the `Zend\Feed\Reader` API is just
Chris@0 626 not capable of getting something you need from a feed or entry. You can use the
Chris@0 627 underlying source objects, like DOMDocument, to get these by hand; however, there
Chris@0 628 is a more reusable method available: you can write extensions supporting these new
Chris@0 629 queries.
Chris@0 630
Chris@0 631 As an example, let's take the case of a purely fictitious corporation named
Chris@0 632 Jungle Books. Jungle Books have been publishing a lot of reviews on books they
Chris@0 633 sell (from external sources and customers), which are distributed as an RSS 2.0
Chris@0 634 feed. Their marketing department realises that web applications using this feed
Chris@0 635 cannot currently figure out exactly what book is being reviewed. To make life
Chris@0 636 easier for everyone, they determine that the geek department needs to extend
Chris@0 637 RSS 2.0 to include a new element per entry supplying the ISBN-10 or ISBN-13
Chris@0 638 number of the publication the entry concerns. They define the new `<isbn>`
Chris@0 639 element quite simply with a standard name and namespace URI:
Chris@0 640
Chris@0 641 - Name: JungleBooks 1.0
Chris@0 642 - Namespace URI: http://example.com/junglebooks/rss/module/1.0/
Chris@0 643
Chris@0 644 A snippet of RSS containing this extension in practice could be something
Chris@0 645 similar to:
Chris@0 646
Chris@0 647 ```xml
Chris@0 648 <?xml version="1.0" encoding="utf-8" ?>
Chris@0 649 <rss version="2.0"
Chris@0 650 xmlns:content="http://purl.org/rss/1.0/modules/content/"
Chris@0 651 xmlns:jungle="http://example.com/junglebooks/rss/module/1.0/">
Chris@0 652 <channel>
Chris@0 653 <title>Jungle Books Customer Reviews</title>
Chris@0 654 <link>http://example.com/junglebooks</link>
Chris@0 655 <description>Many book reviews!</description>
Chris@0 656 <pubDate>Fri, 26 Jun 2009 19:15:10 GMT</pubDate>
Chris@0 657 <jungle:dayPopular>
Chris@0 658 http://example.com/junglebooks/book/938
Chris@0 659 </jungle:dayPopular>
Chris@0 660 <item>
Chris@0 661 <title>Review Of Flatland: A Romance of Many Dimensions</title>
Chris@0 662 <link>http://example.com/junglebooks/review/987</link>
Chris@0 663 <author>Confused Physics Student</author>
Chris@0 664 <content:encoded>
Chris@0 665 A romantic square?!
Chris@0 666 </content:encoded>
Chris@0 667 <pubDate>Thu, 25 Jun 2009 20:03:28 -0700</pubDate>
Chris@0 668 <jungle:isbn>048627263X</jungle:isbn>
Chris@0 669 </item>
Chris@0 670 </channel>
Chris@0 671 </rss>
Chris@0 672 ```
Chris@0 673
Chris@0 674 Implementing this new ISBN element as a simple entry level extension would
Chris@0 675 require the following class (using your own namespace).
Chris@0 676
Chris@0 677 ```php
Chris@0 678 namespace My\FeedReader\Extension\JungleBooks;
Chris@0 679
Chris@0 680 use Zend\Feed\Reader\Extension\AbstractEntry;
Chris@0 681
Chris@0 682 class Entry extends AbstractEntry
Chris@0 683 {
Chris@0 684 public function getIsbn()
Chris@0 685 {
Chris@0 686 if (isset($this->data['isbn'])) {
Chris@0 687 return $this->data['isbn'];
Chris@0 688 }
Chris@0 689
Chris@0 690 $isbn = $this->xpath->evaluate(
Chris@0 691 'string(' . $this->getXpathPrefix() . '/jungle:isbn)'
Chris@0 692 );
Chris@0 693
Chris@0 694 if (! $isbn) {
Chris@0 695 $isbn = null;
Chris@0 696 }
Chris@0 697
Chris@0 698 $this->data['isbn'] = $isbn;
Chris@0 699 return $this->data['isbn'];
Chris@0 700 }
Chris@0 701
Chris@0 702 protected function registerNamespaces()
Chris@0 703 {
Chris@0 704 $this->xpath->registerNamespace(
Chris@0 705 'jungle',
Chris@0 706 'http://example.com/junglebooks/rss/module/1.0/'
Chris@0 707 );
Chris@0 708 }
Chris@0 709 }
Chris@0 710 ```
Chris@0 711
Chris@0 712 This extension creates a new method `getIsbn()`, which runs an XPath query on
Chris@0 713 the current entry to extract the ISBN number enclosed by the `<jungle:isbn>`
Chris@0 714 element. It can optionally store this to the internal non-persistent cache (no
Chris@0 715 need to keep querying the DOM if it's called again on the same entry). The
Chris@0 716 value is returned to the caller. At the end we have a protected method (it's
Chris@0 717 abstract, making it required by implementations) which registers the Jungle
Chris@0 718 Books namespace for their custom RSS module. While we call this an RSS module,
Chris@0 719 there's nothing to prevent the same element being used in Atom feeds; all
Chris@0 720 extensions which use the prefix provided by `getXpathPrefix()` are actually
Chris@0 721 neutral and work on RSS or Atom feeds with no extra code.
Chris@0 722
Chris@0 723 Since this extension is stored outside of zend-feed, you'll need to ensure your
Chris@0 724 application can autoload it. Once that's in place, you will also need to ensure
Chris@0 725 your extension manager knows about it, and then register the extension with
Chris@0 726 `Zend\Feed\Reader\Reader`.
Chris@0 727
Chris@0 728 The following example uses `Zend\Feed\Reader\ExtensionPluginManager` to manage
Chris@0 729 extensions, as it provides the ability to register new extensions without
Chris@0 730 requiring extension of the plugin manager itself. To use it, first intall
Chris@0 731 zend-servicemanager:
Chris@0 732
Chris@0 733 ```bash
Chris@0 734 $ composer require zendframework/zend-servicemanager
Chris@0 735 ```
Chris@0 736
Chris@0 737 From there:
Chris@0 738
Chris@0 739 ```php
Chris@0 740 use My\FeedReader\Extension\JungleBooks;
Chris@0 741 use Zend\Feed\Reader\ExtensionManager;
Chris@0 742 use Zend\Feed\Reader\ExtensionPluginManager;
Chris@0 743 use Zend\Feed\Reader\Reader;
Chris@0 744
Chris@0 745 $extensions = new ExtensionPluginManager();
Chris@0 746 $extensions->setInvokableClass('JungleBooksEntry', JungleBooks\Entry::class);
Chris@0 747 Reader::setExtensionManager(new ExtensionManager($extensions));
Chris@0 748 Reader::registerExtension('JungleBooks');
Chris@0 749
Chris@0 750 $feed = Reader::import('http://example.com/junglebooks/rss');
Chris@0 751
Chris@0 752 // ISBN for whatever book the first entry in the feed was concerned with
Chris@0 753 $firstIsbn = $feed->current()->getIsbn();
Chris@0 754 ```
Chris@0 755
Chris@0 756 Writing a feed extension is not much different. The example feed from earlier
Chris@0 757 included an unmentioned `<jungle:dayPopular>` element which Jungle Books have
Chris@0 758 added to their standard to include a link to the day's most popular book (in
Chris@0 759 terms of visitor traffic). Here's an extension which adds a
Chris@0 760 `getDaysPopularBookLink()` method to the feel level API.
Chris@0 761
Chris@0 762 ```php
Chris@0 763 namespace My\FeedReader\Extension\JungleBooks;
Chris@0 764
Chris@0 765 use Zend\Feed\Reader\Extension\AbstractFeed;
Chris@0 766
Chris@0 767 class Feed extends AbstractFeed
Chris@0 768 {
Chris@0 769 public function getDaysPopularBookLink()
Chris@0 770 {
Chris@0 771 if (isset($this->data['dayPopular'])) {
Chris@0 772 return $this->data['dayPopular'];
Chris@0 773 }
Chris@0 774
Chris@0 775 $dayPopular = $this->xpath->evaluate(
Chris@0 776 'string(' . $this->getXpathPrefix() . '/jungle:dayPopular)'
Chris@0 777 );
Chris@0 778
Chris@0 779 if (!$dayPopular) {
Chris@0 780 $dayPopular = null;
Chris@0 781 }
Chris@0 782
Chris@0 783 $this->data['dayPopular'] = $dayPopular;
Chris@0 784 return $this->data['dayPopular'];
Chris@0 785 }
Chris@0 786
Chris@0 787 protected function registerNamespaces()
Chris@0 788 {
Chris@0 789 $this->xpath->registerNamespace(
Chris@0 790 'jungle',
Chris@0 791 'http://example.com/junglebooks/rss/module/1.0/'
Chris@0 792 );
Chris@0 793 }
Chris@0 794 }
Chris@0 795 ```
Chris@0 796
Chris@0 797 Let's add to the previous example; we'll register the new class with the
Chris@0 798 extension manager, and then demonstrate using the newly exposed method:
Chris@0 799
Chris@0 800 ```php
Chris@0 801 use My\FeedReader\Extension\JungleBooks;
Chris@0 802 use Zend\Feed\Reader\ExtensionManager;
Chris@0 803 use Zend\Feed\Reader\ExtensionPluginManager;
Chris@0 804 use Zend\Feed\Reader\Reader;
Chris@0 805
Chris@0 806 $extensions = new ExtensionPluginManager();
Chris@0 807 $extensions->setInvokableClass('JungleBooksEntry', JungleBooks\Entry::class);
Chris@0 808 $extensions->setInvokableClass('JungleBooksFeed', JungleBooks\Feed::class);
Chris@0 809 Reader::setExtensionManager(new ExtensionManager($extensions));
Chris@0 810 Reader::registerExtension('JungleBooks');
Chris@0 811
Chris@0 812 $feed = Reader::import('http://example.com/junglebooks/rss');
Chris@0 813
Chris@0 814 // URI to the information page of the day's most popular book with visitors
Chris@0 815 $daysPopularBookLink = $feed->getDaysPopularBookLink();
Chris@0 816 ```
Chris@0 817
Chris@0 818 Going through these examples, you'll note that while we need to register the
Chris@0 819 feed and entry classes separately with the plugin manager, we don't register
Chris@0 820 them separately when registering the extension with the `Reader`. Extensions
Chris@0 821 within the same standard may or may not include both a feed and entry class, so
Chris@0 822 `Zend\Feed\Reader\Reader` only requires you to register the overall parent name,
Chris@0 823 e.g. JungleBooks, DublinCore, Slash. Internally, it can check at what level
Chris@0 824 extensions exist and load them up if found. In our case, we have a complete
Chris@0 825 extension now, spanning the classes `JungleBooks\Feed` and `JungleBooks\Entry`.