18 JAN 2011 1
If you aren't already familiar with what RSS stands for then I would highly advise you to have a look at this great article on ProBlogger, then get back to read the rest of the entry. In this article I will also assume you are more or less familiar with Object Oriented Programming and you know some PHP.
Back in the days of PHP 4.x reading an RSS stream would have involved opening a TCP connection to the URI, reading the content and parsing it with an endless stream of regular expressions. PHP 5 allows you to do it seamlessly in a few lines of code with the help of simplexml_load_file().
You will need the libxml extension installed. To check for it, point your browser to the phpinfo page and look for something similar to the image below:
If the extension is not enabled, you will need to recompile PHP with the --enable-libxml argument (or ask your web hosting provider to set it up for you if you are on a shared host). Also, since you will be opening remote XML feeds, you will need allow_url_fopen = on in your php.ini file.
Getting the RSS feed is as simple as
[cc lang="php"][/cc]
For this example, we will be using the Lifeline Design feed. Provided there are no errors, $rss is now a SimpleXMLElement object, with one property we are interested in: $rss->channel contains all information in the RSS feed. $rss->channel is a SimpleXMLElement object as well, with the following properties:
To get the actual posts, you will need to loop through the $rss->channel->item object, which is also an instance of SimpleXMLElement, and read the following properties:
As outlined in the beginning, as little as a few lines of code can do the job:
[cc lang="php"]
$rss = simplexml_load_file('https://www.lifelinedesign.ca/blog/feed/');
if($rss) { echo '
'; //channel title, aka the name of the blog echo 'Last updated on: '.$rss>channel->lastBuildDate; //date of the last post echo '
foreach($rss->channel->item as $item) { //loop through the articles echo '
'; //contents } echo '
'; }
?>
[/cc]
Of course, there is still room for improvement (for example, if there is no feed at that URL, libxml will throw a set of nasty warnings), yet the code can be used to jumpstart your own RSS reader.
Lifeline Design Inc.
@ CSI 192 Spadina Ave.
Toronto, Ontario
M5T 2C7
Phone: 877 543 3110
Email: sales@lifelinedesign.ca
Copyright 2024. All Rights Reserved. Lifeline Design