CodesCompiler
πŸ”
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact πŸš€ Get Started Free

PHP - AJAX RSS Feed Example

PHP - AJAX RSS Feed Example

Really Simple Syndication (RSS)

RSS, which stands for Really Simple Syndication, is used to publish often updated information from website like audio, video, images, etc. We can integrate RSS feeds to a website by using AJAX and PHP. This code demonstrates how to show RSS feeds in our site.

Index.html

The index page should be as follows βˆ’

Preview

rss.php

”rss.php” has contained syntax about how to get access toRSS FeedsRSS Feeds and return RSS Feeds to the webpages.

PHP CODE
<?php
   $q = $_GET["q"];

   if($q == "cnn") {
      $xml = ("http://rss.cnn.com/rss/cnn_topstories.rss");
   } elseif($q == "bbc") {
      $xml = ("http://newsrss.bbc.co.uk/rss/newsonline_world_edition/americas/rss.xml");
   } elseif($q = "pcw"){
      $xml = ("http://www.pcworld.com/index.rss");
   }

   $xmlDoc = new DOMDocument();
   $xmlDoc->load($xml);

   $channel = $xmlDoc->getElementsByTagName('channel')->item(0);

   $channel_title = $channel->getElementsByTagName('title')
   ->item(0)->childNodes->item(0)->nodeValue;

   $channel_link = $channel->getElementsByTagName('link')
   ->item(0)->childNodes->item(0)->nodeValue;

   $channel_desc = $channel->getElementsByTagName('description')
   ->item(0)->childNodes->item(0)->nodeValue;

   echo("<p><a href = '" . $channel_link . "'>" . 
      $channel_title . "</a>");
   echo("<br>");
   echo($channel_desc . "</p>");

   $x = $xmlDoc-&gt;getElementsByTagName('item');

   for ($i = 0; $i&lt;=2; $i++) {
      $item_title = $x-&gt;item($i)-&gt;getElementsByTagName('title')
      -&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue;

      $item_link = $x-&gt;item($i)-&gt;getElementsByTagName('link')
      -&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue;

      $item_desc = $x-&gt;item($i)-&gt;getElementsByTagName('description')
      -&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue;

      echo ("<p><a href = '" . $item_link . "'>" . $item_title . "</a>");
      echo ("<br>");
      echo ($item_desc . "</p>");
   }
?&gt;

It will produce the following output βˆ’