Thursday, August 11, 2011

PHP Example - AJAX RSS Reader

An RSS Reader is used to read RSS Feeds.


Example Explained - The HTML Page

When a user selects an RSS-feed in the dropdown list above, a function called "showResult()" is executed. The function is triggered by the "onchange" event:












RSS-feed will be listed here...


The showResult() function does the following:

  • Check if an RSS-feed is selected
  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to a file on the server
  • Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

The PHP File

The page on the server called by the JavaScript above is a PHP file called "getrss.php":

load($xml);

//get elements from ""
$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;

//output elements from ""
echo("

" . $channel_title . "");
echo("
");
echo($channel_desc . "

");

//get and output "" elements
$x=$xmlDoc->getElementsByTagName('item');
for ($i=0; $i<=2; $i++)
{
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$item_link=$x->item($i)->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$item_desc=$x->item($i)->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;

echo ("

" . $item_title . "");
echo ("
");
echo ($item_desc . "

");
}
?>

When an RSS-feed is sent from the JavaScript, the following happens:

  • Check which feed was selected
  • Create a new XML DOM object
  • Load the RSS document in the xml variable
  • Extract and output elements from the channel element
  • Extract and output elements from the item element

No comments:

Post a Comment