SimplePie: Easily build personalized RSS readers
Farewell to Google Reader? Don't worry! Using PHP's SimplePie library, you can easily create your own RSS readers. This article will guide you to get started quickly and experience the power of SimplePie.
Core points:
get_item()
and get_items()
methods provide two different ways to retrieve data. Additionally, it provides caching options to avoid re-crawling the entire feed every time. Install SimplePie
Install SimplePie using Composer: Add the following code to your composer.json
file:
{ "require": { "simplepie/simplepie": "dev-master" } }
Composer Once the library is downloaded, include the autoload file in your PHP script and you can start writing your RSS reader.
Basic Functions
First, select an RSS or Atom feed and get its URL (for example, the NY Times feed: http://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml
). The following code shows the basic usage of SimplePie:
<?php require_once 'autoloader.php'; $url = 'http://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml'; $feed = new SimplePie(); $feed->set_feed_url($url); $feed->init(); echo '<h1>' . $feed->get_title() . '</h1>'; echo '<p>' . $feed->get_description() . '</p>'; $item = $feed->get_item(0); echo '<p>标题:<a href="' . $item->get_link() . '">' . $item->get_title() . '</a></p>'; echo '<p>作者:' . $item->get_author()->get_name() . '</p>'; echo '<p>日期:' . $item->get_date('Y-m-d H:i:s') . '</p>'; echo '<p>描述:' . $item->get_description() . '</p>'; echo $item->get_content(true); ?>
This code shows how to get the title, description of the feed, as well as the title, link, author, date and content of a single feed entry.
Select item
Theget_item()
method gets a single feed item, while the get_items()
method allows you to get multiple items at once and supports pagination display. For example, the following code shows page 2 in the feed, 3 items per page:
<?php foreach ($feed->get_items(3, 3) as $item) { // 处理每个项目 } ?>
Cache
SimplePie supports caching for improved performance. Just enable the cache function:
<?php $feed = new SimplePie(); $feed->set_feed_url($url); $feed->enable_cache(); $feed->init(); ?>
This will cache the feed data to the cache
directory (must make sure that the directory is writable). You can use the set_cache_location()
method to specify other cache locations.
Summary
SimplePie provides powerful features that allow you to handle RSS/Atom feeds easily. Dig deep into its API documentation and you can create feature-rich personalized RSS readers.
(The following is the FAQ part, which has been streamlined and rewritten)
FAQ:
get_title()
, get_description()
, get_permalink()
, get_items()
, set_feed_url()
error()
Use the enable_cache()
Use the sanitize()
Use the I hope this article can help you get started quickly SimplePie!
The above is the detailed content of PHP Master | Consuming Feeds with SimplePie. For more information, please follow other related articles on the PHP Chinese website!