问题
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! :)
回答1:
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>
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>
来源:https://stackoverflow.com/questions/41028883/limit-the-number-of-rss-feed-to-fetch