我需要有关我在网站上测试的 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/