A PHP Function for Fetching RSS Feed and Outputing Feed Items as HTML

I aggregate all my new posts from several sites into a single RSS feed. Last time I updated my homepage, I came across an idea why not showing these feed items directly on the homepage as HTML content. After some study, I got one single PHP function in my hand that fetches an RSS feed and outputs HTML content in the page.

The PHP fuction and one example are as follows.

The single PHP function that gets RSS feed and converts it to HTML. Another helper function that outputs the HTML content.

One usage example:

<?php
// output RSS feed to HTML
output_rss_feed('http://feeds.systutorials.com/ericfeed', 20, true, true, 200);
?>

Here is one example showing how to use this script.

The comments in the code should explain what it does well. You can call the output_rss_feed with the feed link and other options at the place where you would show the RSS feed.

This function also supports a simple caching mechanism so that not every call to the same RSS feed will invoke a network request.

For the style of the items displayed, you may customize your site’s CSS file or add add a style tag to control the styles. The code already generate class names for most items. Here is one example of the CSS for customizing the style of the displayed feed items.

.feed-description {padding-left:10px;margin-left:10px;border-left:2px solid #eee;}
.feed-lists {padding-left:1em;}
.feed-item-image {max-width: 300px; max-height: 200px; float: right; margin-left: 10px; }

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

46 comments:

  1. Hello there! I am using this on one site, but I have problems with the Norwegian characters in the titles of the blog posts, because the special norwegian letters æ, ø and å shows up in a not nice way. Do you know anything that can be done for this to work? And if I would want the dates of the publishing to show up following Norwegian standards, what can I do for this to happen?

    http://norsk.worldcityguides.net/

    Thanks a lot for the brilliant script!

    1. Hi Siggi,

      You will need some PHP debugging then.

      For the characters problem, you may take a look at this line which possible causes this:

      $title = str_replace(' & ', ' & ', $feed[$x]['title']);

      Or you may add additional character encoding/decoding function for the $title.

      For date format, you may change the format in this line:

      $date = date('l F d, Y', strtotime($feed[$x]['date']));
  2. Well, l’m not sure what I’m asking. It worked locally with wp feeds. But now in production is not. Is creating an empty rss2html- file with just one line on it.

    Thanks again.

  3. Seems to be an encoding error since the blog is in spanish. Does not happen with your blogs feed. Can you point me how to fix it?

    Thank you!

      1. Well, the feed validated with 2 recommendation warnings. Finally I created a new feed URL with Feedburner and now is working properly.

        Thank you!

  4. Worked fine. Straight-forward even though php is not my language (yet).

    I like the fact that you took the time to put in CSS class names. I went back to do it myself and constrain some image sizes on the feed I used and found the classes already there. Nice!

    Thanks,
    j

  5. Hi

    I have used the code as it is (except to add the URL to my sites RSS feed). I get title, description, date and link no problem but no images. I have a jpg image in the post and I have another jpg image set as “featured”. Am I missing something here? Is there something I need to do in WP to make the image available on the RSS feed?

    may be a simple answer but I am completely new to WP, RSS, PHP….everything really :-)

    Thanks

    1. The image displayed is the one inside of the description part of the feed. If your feed has no image in the description, it is not displayed by this script. Please feel free to fork a copy and revise it according to your need.

      1. I am not a coder as I mentioned earlier. How would I need to modify the code to pull the “featured” image instead of the image from the actual post content?

        Thanks

  6. Hi. Good code .. works splendid… except for image for rss 2.0
    it does not support rss 2.0 ?

    1. The example image’s css is a combination of the page’s style and some small additional style for the generated feed list/items.

      The following is the CSS code I found which might not be exactly what was used. But it should be quite close to it.

      .feed-description {padding-left:10px;margin-left:10px;border-left:2px solid #eee;}
      .feed-lists {padding-left:1em;}
      .feed-item-image {max-width: 300px; max-height: 200px; float: right; margin-left: 10px; }
      
  7. Hi,

    Great stuff Eric. Congrats!

    May I suggest for a future tutoral. A way to do this but pull the entire feed. As you know most RSS feeds are limited to the tittle, image and introductory text. The feeds themselves don’t contain the full text of the articles.
    If there is a PHP function to fetch the URL of the feed entry and extracting the full text from there?

    Thanks

    1. Thanks Ivanux.

      Your idea is good. But the logic may need to be implemented specifically for the targeting site because getting the “full text” from a URL accurately depends on the design and structure of the site. The case is different from the feed description whose structure is clearly defined.

      The `DOMDocument()` object and its `load()` method can be used to fetch the URL for a feed entry. For the DOM for a page, the text can be extracted out following the site’s structure.

  8. Question, in my RSS feed the correct author output comes from an item field called “dc:creator” (e.g. Marl). The colon is a bit tedious and I’m not sure how to modify your code to pull this data.

  9. Good day, have be using your wonderful script for a while now, but I upgraded my PHP to 7.3 today and the script stopped working. Any suggestions on what to check?

      1. Please disregard, I think there was some other issue with my web host, it is now working today. Sorry for any inconvenience, and again thank you for a wonderful script.

  10. I was hoping to be able to easily add multiple feeds and get it to work on my own but I have failed to get it to work.Could someone explain to a php dummy what I need to modify/change to get 3-10 feeds to work if possible.

    Thanks for your time

    1. One method is to use rssmix http://www.rssmix.com/ to aggregate multiple RSS feeds into a single one and then show them in the page using the script here if you want to show them as a single one feeds.

      If you would like to show them as multiple feeds, just call the `output_rss_feed` function for multiple times for these feeds.

      1. I am getting this when I put a feed into the bottom where it has

        $feed_url,

        Parse error: syntax error, unexpected ‘:’, expecting ‘)’ inXXXXXX/feedreader/option4/reader.php on line 93

      2. Eric, would you possibly be abe too send me a txt file or a zip of the script with one feed in it and working ? I just can’t seem to add the url for a feed and have it work.

        I always get an error of one type or another. I must be missing something but I do not know where to look due to the little bit of experience I have had with PHP.

        Thank you

  11. What code would need to be added to get links open in new window and no follow tags?
    load(‘https://rest.ebay.com/epn/v1/find/item.rss?keyword=Abbyson+Living&sortOrder=BestMatch&programid=1&campaignid=5338305914&toolid=10039&listingType1=AuctionWithBIN&listingType2=FixedPrice&descriptionSearch=true&feedType=rss&lgeo=1’);
    $feed = array();
    foreach ($rss->getElementsByTagName(‘item’) as $node) {
    $item = array (
    ‘title’ => $node->getElementsByTagName(‘title’)->item(0)->nodeValue,
    ‘desc’ => $node->getElementsByTagName(‘description’)->item(0)->nodeValue,
    ‘link’ => $node->getElementsByTagName(‘link’)->item(0)->nodeValue,
    ‘date’ => $node->getElementsByTagName(‘pubDate’)->item(0)->nodeValue,
    );
    array_push($feed, $item);
    }
    $limit = 40;
    for($x=0;$x<$limit;$x++) {
    $title = str_replace(' & ', ' & ', $feed[$x]['title']);
    $link = $feed[$x]['link'];
    $description = $feed[$x]['desc'];
    $date = date('l F d, Y', strtotime($feed[$x]['date']));
    echo 'A PHP Function for Fetching RSS Feed and Outputing Feed Items as HTML‘;
    echo ‘Posted on ‘.$date.’‘;
    echo ”.$description.”;
    }
    ?>

    1. I got it working due to your help and the example you posted.

      I appreciate it very much.

      Now I will try and add more feeds and keep them grouped by feed.

  12. Okay, I got it to work using 2 feeds and now need to add some styling by way of css.Is there an easier way to add css to this the standard way ass a css file ( like where would i put it and how) and can I set it do put a custom headline for each feed source like:

    CNN News
    BBC News

    I am a student trying to learn from you pros …

    Thanks for allowing me to ask questions

    1. Okay, I figured out how to add the css file to the script but I am still looking for a way to put A headline for the name of each feed.An example is CNN News or Fox Sports….

  13. Hi Eric, really thanks for sharing your work.
    i’m trying to integrate your code in a WP site in a widget that support both PHP and HTML.

    it works perfectly, but i’m facing a behavior that i can’t explain (considering i’m not a dev): i need to store the output_rss_feed function in a variable to check if the feedback is embpty or not prior to show the content.

    doing so, using the simple $myvar = output_rss_feed(‘https://mysite/feed/’, 20, true, true, 200) the rss is displayed anyway, and I didn’t found a way to enter in the if statement. I also tryed with if(!empty(output_rss_feed(‘https://mysite/feed/’, 20, true, true, 200))) and i face the same behavior.

    do you have any suggestion to work around this?
    thanks a lot

  14. Okay, I figured out how to add the css file to the script.But I am unsure of how to put an name for each feed like I mentioned previously.

    I will keep trying to figure it out

Leave a Reply

Your email address will not be published. Required fields are marked *