SimplePie: combine multiple feeds, but with a different number of items for each feed

StackOverflow https://stackoverflow.com/questions/21698470

  •  09-10-2022
  •  | 
  •  

Question

I'm trying to display two (currently, but this number may increase) feeds using SimplePie. I'm using what I think is SimplePie's preferred way of doing multiple feeds, and it is working well - as long as I am happy with having the same number of items displayed from each feed.

However, I would like to have flexibility to tell SimplePie to display the output of the two combined feeds, but to take 10 items (for example) from one feed, and only 5 from the other, so that the combined output is biased towards one (more important) source. What do you think is the best way to do that?

Here is my current code. It uses a multiple feeds object, but I am happy to use individual SimplePie objects if that is more sensible.

<?php
require_once('simplepie/autoloader.php');

// Create a new SimplePie object
$feed = new SimplePie();

$feed->set_feed_url(array(
    'http://example.com/feed1.rss',
    'http://example.com/feed2.rss'
));

$feed->set_item_limit(5);
$feed->init();
$feed->set_cache_location('/var/www/simplepie/library/cache');
$feed->set_cache_duration(600);
$feed->handle_content_type();

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Feed test</title>
</head>

<body>
    <?php
    // Begin feed output

    foreach ($feed->get_items() as $item):

        $authorObject = $item->get_author();
        $author = $authorObject->get_name();

        $feed = $item->get_feed();

        // Rest of the code removed
    ?>
</body>
Was it helpful?

Solution

There is a function to limit the number of items pulled per feed: set_item_limit()

$feed->set_item_limit(5);

However, this pulls the same number of articles from each feed. You could set that to 10 or whatever you want your max to be. The only way I can think of (off the top of my head) to do what you want is to set your own counters in the get_items loop and each time through check something in the feed data like the url or something.

$cntr1 = 0;
$cntr2 = 0;
foreach ($feed->get_items() as $item) {
    if ($cntr1 <= 5 && strstr($item->get_feed()->get_permalink(), [your search criteria])) {
        // do your fetch of the item stuff for feed 1
        $cntr1++;
    }
    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top