限制要提取的RSS提要的数量 [英] Limit the number of RSS feed to fetch

查看:124
本文介绍了限制要提取的RSS提要的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助,我正在我的网站上测试的RSS阅读器的代码,脚本工作正常,但它显示20饲料,我想限制它到我设置的数字(例如3或6)。

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! :)

推荐答案

如果您想限制结果,只需在循环中添加计数器和中断:

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>

或者使用 array_splice 切割数组:

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>

这篇关于限制要提取的RSS提要的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆