如何限制饲料?

时间:2012-08-14 16:49:21

标签: php rss feed

我正在建立一个网站来学习PHP,我正在将一个合并-rss-feeds制作成一个我可以在我的网站上显示的Feed。

以下是代码:

<?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限制?

1 个答案:

答案 0 :(得分:2)

将你的foreach改为for(i = 0; i&lt; 5; i ++)循环。另一种可能性:引入一个计数器变量,在foreach开始时递增并测试。当它达到5时突破循环。