Dani
1 min read
January 30, 2024 (last revised)
How to Fetch and Display RSS Feed in WordPress with PHP
RSS feed is a standardized format for delivering regularly updated content from websites. By incorporating RSS feeds into your website, you can pull in content from external sources, such as news articles or blog posts, keeping your audience informed and engaged.
The PHP Snippet:
Below is a PHP snippet that fetches and displays a feed using the SimpleXMLElement
class in PHP. This example assumes you have the URL of the RSS you want to integrate.
<?php
function fetchAndDisplayRSSFeed($feedURL, $numItems = 5) {
// Fetch the RSS feed
$rss = simplexml_load_file($feedURL);
// Check if the feed was successfully loaded
if ($rss !== false) {
// Output the title and description of the RSS feed
echo "<h2>{$rss->channel->title}</h2>";
echo "<p>{$rss->channel->description}</p>";
// Loop through the items and display them
for ($i = 0; $i < $numItems; $i++) {
$item = $rss->channel->item[$i];
echo "<h3>{$item->title}</h3>";
echo "<p>{$item->description}</p>";
echo "<p><a href='{$item->link}' target='_blank'>Read more</a></p>";
// Additional information such as pubDate can also be displayed
// For example: echo "<p>Published on: {$item->pubDate}</p>";
echo "<hr>";
}
} else {
// Display an error message if the feed cannot be loaded
echo "<p>Error loading the RSS feed.</p>";
}
}
// Example usage:
$feedURL = 'https://example.com/rss-feed.xml'; // Replace with the actual RSS feed URL
fetchAndDisplayRSSFeed($feedURL);
?>
How to Use the Snippet:
- Replace
'https://example.com/rss-feed.xml'
with the actual URL of the RSS you want to display. - Integrate the PHP snippet into your website where you want the RSS feed content to appear.