What approach should be taken to display the last 5 news titles from an RSS feed using PHP?
To display the last 5 news titles from an RSS feed using PHP, you can use the SimpleXML extension to parse the XML data from the feed. You can then loop through the items and display the titles accordingly. Make sure to handle any errors that may occur during the parsing process.
<?php
$url = 'https://example.com/rss-feed'; // URL of the RSS feed
$xml = simplexml_load_file($url);
if ($xml) {
$items = $xml->channel->item;
$count = count($items);
$start = ($count > 5) ? $count - 5 : 0;
for ($i = $start; $i < $count; $i++) {
echo $items[$i]->title . "<br>";
}
} else {
echo "Failed to load RSS feed.";
}
?>
Keywords
Related Questions
- When restructuring existing PHP code for better clarity and functionality, what considerations should be taken into account to ensure the desired outcome is achieved without introducing new errors?
- What best practices should be followed when setting cookies in PHP to ensure smooth functionality and avoid header modification errors?
- What are best practices for form processing in PHP, especially when dealing with a large number of input fields?