Embedding RSS Feeds into your PHP Pages Using SimplePie
If you are building a site in PHP and wish to embed an RSS feed, such as a list of recent news headlines, into your page output, you can do so with the SimplePie library. SimplePie is a free RSS parsing library for PHP that makes adding the output of an RSS feed into your pages simple and efficiant. Before you begin, you will need to enable the "allow_url_fopen" option for PHP. To do so, create a new text file in the /etc/php.d/ directory called "allow-url-fopen.ini" with the following contents: allow_url_fopen = On Once you have created this file, restart your VDS using the Web Server link on the left side of the VDS Manager. If you do not restart the web server after making this change, your scripts may not function as expected. You can download SimplePie to your computer from the official website: http://simplepie.org/downloads/?download Open the ZIP file that is downloaded and extract the 'simplepie.inc' file. This is the only file you will need to include in your PHP pages. Once you have extracted it, upload it to your web hosting account into the same directory as your PHP script that you wish to use for RSS output. In your PHP script, you will first need to load the SimplePie library with the following code: <? require_once('simplepie.inc'); ?> Now, you just need to create a new instance of the parser, set any options you'd like, and initialize the instance you've created. <? $feed = new SimplePie(); $feed->feed_url('http://yourdomain.com/feed.xml'); // This variable specifies the location of your RSS feed; set it accordingly. $feed->cache_location('/tmp/rss-cache'); // This optional variable tells SimplePie to cache the entries $feed->init(); ?> Now that the data has been retrieved and parsed, you can process it and output it to your page. <? foreach($feed->get_items() as $item) { $title = mysql_escape_string($item->get_title()); $link = mysql_escape_string($item->get_permalink()); $body = mysql_escape_string($item->get_description()); } ?> Here is an example script which will output news headlines into your page, without using any cache on the server. <? require_once('simplepie.inc'); $feed = new SimplePie(); $feed->feed_url('http://rss.cnn.com/rss/cnn_topstories.rss' ); $feed->order_by_date(false); $feed->bypass_image_hotlink(false); $feed->init(); if ($feed->data) { $items = array_reverse($feed->get_items()); foreach($items as $item) { $title = $item->get_title(); $link = $item->get_permalink(); $body = $item->get_description(); $date = $item->get_date("j F Y g:i a"); echo "<a href='$link'>$title</a><br />$date<br />$body<br /><br />"; } } ?> A complete list of SimplePie functions and examples can be found on the developers website at http://simplepie.org/docs/reference/ |



