Fetching RSS Feed and Outputing Feed Items as HTML in PHP

Posted on In Programming, Tutorial, Web

It is useful to show the feed items directly on the webpage as HTML content. In this ost, we will show one single PHP function that fetches an RSS feed and outputs the feed items as HTML elements in the web page. One example to fetch an RSS feed and output the itmes as HTML using PHP is as follows in the image.

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.feedburner.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.

53 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. Hi,

    I’m getting an empty feed with wordpress feeds. Is this an error? or is WP denying it?

    Thank you!

  3. 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.

  4. 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!

  5. 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

  6. 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

        1. Hi, I just had the same problem. It is maybe because WP doesn’t automatically input the ft image in the RSS. Try with a plugin or add a function in your theme function.php file (ATTN : might not work, it depends on the theme and might break it too so be cautious!! ).
          I ended up using a plugin and the image is now output.
          Wonderful script systutorials BTW . Thank you xxx to the author Eric Z Ma.

  7. 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; }
      
  8. 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.

  9. 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.

  10. Pingback: PHP Function for Fetching RSS Feed and Outputting Feed Items as HTML | PHP Video Academy
  11. 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.

  12. 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

  13. 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.

  14. 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….

  15. 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

  16. 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

  17. Hello Eric,
    First of all, thanks for sharing the code. I would like to use your code in a WordPress widget that I have created. I would love to get the URL from input on my widget. Could you please tell me how I can do that. I am new to PHP.

    Here is my form code:

    public function form( $instance ) {
    $rssurl = ! empty( $instance[‘rssurl’] ) ? $instance[‘rssurl’] : esc_html__( ”, ‘feed_domain’ );
    ?>

    <input id="get_field_id( ‘rssurl’ ) ); ?>” name=”get_field_name( ‘rssurl’ ) ); ?>” type=”text” value=””>

    Here is your code:

    Thanks a lot for your help.
    Mahmoud

  18. This is very cool, but I hope you know, becasue of your first line, this shows up in results for loading multiple feeds into one feed, but your script doesn’t actually have this functionality. It would be nice if this pertains to your first statement, and exploded the feed string by commas, and then iterated all feeds associated, adding them to an array, sorted by pubDate, and then added to a result var.

  19. There are many tools to aggregate RSS feeds already. This function here focus on showing the RSS feed items as HTML. I would keep this function simple to serve a single functionality. Thanks for the comments all the same. I revised the 1st paragraph a little bit to make it clearer.

Leave a Reply

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