Limit the number of RSS feed to fetch

时光怂恿深爱的人放手 提交于 2019-12-11 08:35:35

问题


I need help with the code of the RSS reader i'm testing on my site, the script work fine but it show 20 feed and i wanted to limit it to a number i set (like 3 or 6 for example).

The code it's this:

<?php
    //Feed URLs
    $feeds = array(
        "https://robertsspaceindustries.com/comm-link/rss",
    );

    //Read each feed's items
    $entries = array();
    foreach($feeds as $feed) {
        $xml = simplexml_load_file($feed);
        $entries = array_merge($entries, $xml->xpath("//item"));
    }

    //Sort feed entries by pubDate
    usort($entries, function ($feed1, $feed2) {
        return strtotime($feed2->pubDate) - strtotime($feed1->pubDate);
    });



    ?>



    <ul><?php
    //Print all the entries
    foreach($entries as $entry){
        ?>
        <li><a href="<?= $entry->link ?>"><?= $entry->title ?></a> (<?= parse_url($entry->link)['host'] ?>)
        <p><?= strftime('%m/%d/%Y %I:%M %p', strtotime($entry->pubDate)) ?></p>
        <p><?= $entry->description ?></p>
        <img src="<?= $entry->children('media', true)->content->attributes()->url ?>" alt="" />

        </li>

        <?php
    }
    ?>
    </ul>

i tryed to search for a solution using a variable but i failed... thank you for your help! :)


回答1:


Just add counter and a break in the loop if you want to limit the results:

<ul>
<?php 
$i = 0; // 3 - 6
// Print all the entries
foreach($entries as $entry) { 
    $i++;
?>
    <li>
        <a href="<?= $entry->link ?>"><?= $entry->title ?></a> (<?= parse_url($entry->link)['host'] ?>)
        <p><?= strftime('%m/%d/%Y %I:%M %p', strtotime($entry->pubDate)) ?></p>
        <p><?= $entry->description ?></p>
        <img src="<?= $entry->children('media', true)->content->attributes()->url ?>" alt="" />
    </li>
<?php 
    if($i === 3) break;
} 
?>
</ul>

Or just cut the array using array_splice:

<ul>
<?php 
$entries = array_splice($entries, 0, 3);
// Print all the entries
foreach($entries as $entry) { ?>
    <li>
        <a href="<?= $entry->link ?>"><?= $entry->title ?></a> (<?= parse_url($entry->link)['host'] ?>)
        <p><?= strftime('%m/%d/%Y %I:%M %p', strtotime($entry->pubDate)) ?></p>
        <p><?= $entry->description ?></p>
        <img src="<?= $entry->children('media', true)->content->attributes()->url ?>" alt="" />
    </li>
<?php } ?>
</ul>


来源:https://stackoverflow.com/questions/41028883/limit-the-number-of-rss-feed-to-fetch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!