Differences between SimplePie and SimpleXMLElement
If you need to import external feeds on your web site you have many ways to choose from: IMHO there are just 2 of them that are really interesting.
The 1st method – working on all platforms – is a PHP function to parse XML documents: called SimpleXMLElement, lets you to manually select elements in an array.
I used it in the past and I’ll explain why I changed my mind recently: if you want to take the maximum control of the output and you haven’t a WordPress-powered blog, you could easily choose this way.
Here’s how it works in details: below is just an example — you can change elements following this guidelines.
<?php
$count = 1;
$feed = file_get_contents ( 'http://domain.ext/path/to/feed' );
$rss = new SimpleXmlElement ( $feed );
if ( $rss->channel->item && ( $rss->channel->item != '' ) ) {
foreach ( ( $rss->channel->item) as $item ) {
if ( $count<=5 ) {
echo '<a href="' . $item->link . '">' . $item->title . '</a>';
$count++;
} else {
break;
}
}
} else {
echo 'No items to display.';
}
?>
As you may notice, I included $count to limit the number of displayed items: this is particularly useful for sidebar’s lists and/or if you can’t choose the items number otherwise.
If you don’t need this, just remove lines 2, 7, 9 and 13. The 2nd method to do the same is via SimplePie: the library is actually used by WordPress — so you don’t need anything else, if you’re on it.
Of course, you can install SimplePie separately with every CMS or, plain PHP site:
<?php
include_once ( ABSPATH . WPINC . '/feed.php' );
$rss = fetch_feed ( 'http://domain.ext/path/to/feed');
$count = $rss->get_item_quantity ( 5 );
$items = $rss->get_items ( 0, $count );
if ( $count==0 ) {
echo 'No items to display.';
} else {
foreach ( $items as $item ) {
?>
<a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></a>
<?php
}
}
?>
The code length is quite the same for both the ways, but I think that SimplePie is preferable: line 2 of the above example is only required by WordPress (you need to change it accordingly on other platforms).