【问题标题】:Limit the number of RSS feed to fetch限制要获取的 RSS 提要的数量
【发布时间】:2016-12-08 08:57:26
【问题描述】:

我在我的网站上测试的 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>

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

【问题讨论】:

  • 如果需要,只需在foreach 上添加break$i = 0; foreach(){$i++; if i = 3 break} 或剪切阵列、切片或拼接

标签: php html xml rss simplexml


【解决方案1】:

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

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

【讨论】:

  • 非常感谢幽灵!你真是个天才!我试图支持答案,但我需要 15 的声誉......
  • @fabiobinotti 很高兴这有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多