In the provided PHP code, how can the loop be modified to display only the first 5 news titles from an RSS feed?
To display only the first 5 news titles from an RSS feed in the provided PHP code, you can add a counter variable to track the number of titles displayed and break out of the loop once it reaches 5. This can be achieved by incrementing the counter within the loop and using an if statement to check if the counter is greater than 5 before displaying each title.
<?php
$rss = simplexml_load_file('https://example.com/rss-feed.xml');
$counter = 0;
foreach ($rss->channel->item as $item) {
if ($counter >= 5) {
break;
}
echo $item->title . "<br>";
$counter++;
}
?>