PHP RSS 获取并显示多个 RSS 频道的标题


PHP RSS get and display title of multiple RSS channels

我有以下代码:

        $rss[] = $this->rssparser->set_feed_url('someUrl')->set_cache_life(30)->getFeed(4);
        $rss[] = $this->rssparser->set_feed_url('someURL')->set_cache_life(30)->getFeed(3);
        $rss[] = $this->rssparser->set_feed_url('someURL')->set_cache_life(30)->getFeed(5);

它们中的每一个都以不同的div显示,我想要的是相关频道的标题显示在相关div中。

到目前为止,我有:

foreach ($rss as $feed)
{
    $channel = $this->rssparser->channel_data['title'];
    $result = "<div class='rssFeed'>";
    $result .= '<h3>'.$channel.'</h3>';
    foreach ($feed as $item)
         {  
        $result .= '<div class="rssContent">
            <a href="'.$item['link'].'">'.$item['title'].'</a>
            <br />
            <span>'.$item['pubDate'].'</span>
            </div>
            ';
        }
            $result .= '</div>';
            echo $result;
        }

但这只显示顶部数组最后一个通道的标题......

有人知道我做错了什么吗?

您可以在获取下一个 Feed 之前存储频道标题。例如:-

<?php
class Controller
{
    public function action()
    {
        $feeds = array(
            array('url' => 'http://example.org/feed.rss', 'count' => 3),
            array('url' => 'http://example.org/feed.rss', 'count' => 4),
            array('url' => 'http://example.org/feed.rss', 'count' => 5),
        );
        $rss = array();
        foreach ($feeds as $feed) {
            $rss[] = array(
                'items' => $this->rssparser->set_feed_url($feed['url'])->set_cache_life(30)->getFeed($feed['count']),
                'title' => $this->rssparser->channel_data['title'],
            );
            $this->rssparser->clear();
        }
    }
}

然后,您将像这样迭代提要:-

<?php foreach ($rss as $feed): ?>
    <h1><?php echo $feed['title']; ?></h1>
    <?php foreach ($feed['items'] as $item): ?>
        <a href="<?php echo $item['link']; ?>">
            <?php echo $item['title']; ?>
        </a>
    <?php endforeach; ?>
<?php endforeach; ?>