php - 限制要获取的 RSS 提要数量

标签 php html xml rss simplexml

我需要有关我在网站上测试的 RSS 阅读器代码的帮助,该脚本工作正常,但它显示 20 个提要,我想将其限制为我设置的数字(例如 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>

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

最佳答案

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

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

关于php - 限制要获取的 RSS 提要数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41028883/

相关文章:

php - 多步骤php表单

php - 如何将 mysql 结果打印到屏幕上并仅显示列的一次迭代?

php - MySQL 和 PHP 多个 list 数据库插入

html - 如何使用 flexbox 使部分响应?没有框架

HTML/CSS 表格显示问题

python - 在python中创建xml文件时如何插入制表符而不是空格

php - php中的对象问题

html - 这可以用 CSS 实现吗?

html - 如何用 HTML 和 JavaScript/JQuery 替换数据库以创建动态相关的下拉选择列表?

java - 旋转动画无法正常工作