我正在建立一个网站来学习 PHP,并且正在将 combine-rss-feeds 制作成一个可以在我的网站上显示的提要。
这是代码:
<?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; ?>
这是一个很棒的脚本,运行良好,但它在我的网站上占用了很多空间。如何将其限制为仅显示 5 个结果,有点像 MySQL 限制?