限制要提取的RSS提要数

时间:2016-12-07 22:57:59

标签: php html xml rss simplexml

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

代码就是这样:

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

我尝试使用变量搜索解决方案,但我失败了...... 谢谢您的帮助! :)

1 个答案:

答案 0 :(得分:2)

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

<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剪切数组:

<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>