I'm building a website to learn PHP and am making a combine-rss-feeds into one feed that I can display on my website.
Here's the code:
<?php
class Feed_Amalgamator
{
public $urls = array();
public $data = array();
public function addFeeds( array $feeds )
{
$this->urls = array_merge( $this->urls, array_values($feeds) );
}
public function grabRss()
{
foreach ( $this->urls as $feed )
{
$data = @new SimpleXMLElement( $feed, 0, true );
if ( !$data )
throw new Exception( 'Could not load: ' . $feed );
foreach ( $data->channel->item as $item )
{
$this->data[] = $item;
}
}
}
public function amalgamate()
{
shuffle( $this->data );
$temp = array();
foreach ( $this->data as $item )
{
if ( !in_array($item->link, $this->links($temp)) )
{
$temp[] = $item;
}
}
$this->data = $temp;
shuffle( $this->data );
}
private function links( array $items )
{
$links = array();
foreach ( $items as $item )
{
$links[] = $item->link;
}
return $links;
}
}
/********* Example *********/
$urls = array( 'http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/teams/m/man_city/rss.xml', 'http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/teams/l/liverpool/rss.xml' );
try
{
$feeds = new Feed_Amalgamator;
$feeds->addFeeds( $urls );
$feeds->grabRss();
$feeds->amalgamate();
}
catch ( exception $e )
{
die( $e->getMessage() );
}
foreach ( $feeds->data as $item ) :
extract( (array) $item );
?>
<a href="<?php echo $link; ?>"><?php echo $title; ?></a>
<p><?php echo $description; ?></p>
<p><em><?php echo $pubDate; ?></em></p>
<?php endforeach; ?>
It's a great script, works perfectly, but it takes up quite a lot of space on my website. How can I limit it to only displaying, say 5 results, kind of like a MySQL limit?
Change your foreach to a for(i=0; i<5; i++) loop. The other possibility: introduce a counter variable that you increment and test at the start of the foreach. Break out of the loop when it hits 5.