Jump to content

Recommended Posts

Here is a snippet I use to display an xml feed on another page. I need to know how to make it only show the first 5 items in the feed rather than all of them:

 

<?php
require_once "XML/RSS.php";
$file=file_get_contents('http://mypage.com/wordpress/?feed=rss2');
$r=& new XML_RSS($file);
$r->parse();

//echo '<pre>';
//print_r($r);
//echo '</pre>';
$i=0;



foreach($r->getItems() as $entry)
{

echo '<div class="infoblock">';
echo "<p>";
echo '<a  style="font-size: 130%;" href="';
echo $entry['link'];
echo '">';
echo $entry['title'];
echo "</a></p>";
$line=$entry['content:encoded'];
$line=str_replace('/>','>',$line);
$line=str_replace('</p>','</p><p> </p>',$line);
echo $line;

echo "<p style='text-align: center;'><a href='".$entry['comments']."'>Click here for comments or to leave a reply</a></p><p> </p>";
echo "</div>\n";

}

?>

 

I know this is where the items come from

 

foreach($r->getItems() as $entry)

 

but I don't know how to make the foreach also do while $i < 5 or whatever...

 

Thanks in advance.

Link to comment
https://forums.phpfreaks.com/topic/166582-solved-limit-xml-feed/
Share on other sites

You can use a while() loop, a for() loop, or just add an incremented number into your foreach() like..

 

$i = 0;
foreach($r->getItems() as $entry)
{
         if($i >= 5) break;
echo '<div class="infoblock">';
echo "<p>";
echo '<a  style="font-size: 130%;" href="';
echo $entry['link'];
echo '">';
echo $entry['title'];
echo "</a></p>";
$line=$entry['content:encoded'];
$line=str_replace('/>','>',$line);
$line=str_replace('</p>','</p><p> </p>',$line);
echo $line;

echo "<p style='text-align: center;'><a href='".$entry['comments']."'>Click here for comments or to leave a reply</a></p><p> </p>";
echo "</div>\n";
$i++;
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.