Use PHP and Ajax to create an RSS aggregator code _php instance

Source: Internet
Author: User
Tags http request php language md5 md5 encryption mkdir php class readable
Imagine using a simple HTML file to send a request to a server-side script, receive a custom XML file based on the request, and then display it to the user with little need to refresh the browser! The author of this article will explore with you how to combine PHP and Ajax techniques in a common Web application to create real-time data transfers without the need for browser refreshes.
Although this article uses the PHP language, keep in mind that any server-side language will work correctly. To understand this, I assume you have a basic understanding of JavaScript and PHP or a similar server-side language.
This example uses AJAX to send a request from an RSS feed to a certain PHP object. The PHP object copies a copy of the feed on the local server and returns the path. The request object receives this path, analyzes it, and displays the data as HTML to the user. This sounds a lot of steps, but it's only made up of 4 small files. The 4 small files are used to balance their specific strengths and make the entire system highly efficient.
I think some readers may ask why you want to create a copy of the feed on the local server instead of simply analyzing the original feed. The reason for this is that the cross-domain restrictions imposed by the XML HTTP request object can be allowed to be bypassed. Later, I'll explain how to create this custom PHP object, but first, let's start with the form creation.
Create a form that makes a request
The first thing you need to do is to include JavaScript and any CSS files that you might want to use between your HTML head tags. I included a model table to implement the final layout of the aggregator and make a request and feed analysis using a JavaScript file:
<link href= "Css/layout.css" rel= "stylesheet" type= "Text/css"/>
<script src= "Js/request.js" ></script>
Next, create a form that makes a request for an RSS feed of your choice. The form I created consists of an input field and a button that submits the request. The query for the request is a string that consists of a feed input value and a password word that will be validated on the server side; As an example, I used the following form:
The code makes a request every time the page loads, so if the page is refreshed, the existing feed string in the input field will be requested when the page loads. The following is an example of a form data, along with some div tags to display specific nodes for the parsed feed:
Copy Code code as follows:

<body onload= "javascript:makerequest (' request.php?request= ' + document.feedForm.feed.value + ' password= MyPassword '); " >
<form name= "Feedform" method= "post" action= "Javascript:makerequest" (' request.php?request= ' + Document.feedForm.feed.value + ' Password=mypassword '); " >
Enter a feed: <input type= "text" name= "feed" id= "feed" size= ">"
<input type= "Submit" name= "Submit" value= "Add Feed" >
<div id= "logo" ></div>
<div id= "Copy" ></div>
<div id= "Details" ></div>

The three div tags I created are logo,copy and details, each of which has a style associated with it in the layout style sheet. They will be used when we analyze the feeds, but we first need to be able to access the feeds we request. This can be done using the PHP object I mentioned earlier.
Create a custom PHP object
I used PHP to create a small RSS class that creates a copy of the request feed on the local server so that it can be accessed for the XML HTTP request object that we are going to create later. Typically, you cannot request a file across domains, which means that the file you are requesting needs to reside on the local server. This class is a way to resolve a cross-domain problem because it creates a copy of the feed that is requested on the local server and returns the local path to the feed, which is then accessed by the request object.
The only method in this class is a request method, which has only one parameter that points to the URL of the requested RSS feed. It then checks whether a directory resides on the local server by the name of the RSS. If it does not exist, create one and set its permission mode to 0666, which means that the directory is readable and writable. When set to readable, the directory can be accessed at a later time, and when it is set to writable, a copy of the feed can be written to a directory on the local server:
Copy Code code as follows:

If no directory exists, create a
$dir = "RSS";
if (!is_dir ($dir))
mkdir ($dir, 0666);

On a Windows machine, the mode setting is not required for PHP 4.2.0 and above versions. However, if it exists, it will be ignored; therefore, I reserve it for the project to be migrated to a UNIX or Linux server.
We need a unique file name before copying the feed to the server. I used the MD5 encryption method for this complete URL to make sure that the name of all feeds is unique. With this new filename, it can connect a string that describes the directory that points to the file, which will be used when the copy of the feed is created:
Copy Code code as follows:

Create a unique named
$file =md5 ($rss _url);
$path = "$dir/$file. xml";

We can now create a copy of the file by using a reference to the URL that is defined on the path above and to the original requested feed. Finally, the path is returned to the new file as a response to the request:
Copy Code code as follows:

//copy feeds to local server  
copy ($rss _url, "$path"); 
return $ path; 
following is the small, yet powerful rss class in  its entirety: 
class rss 

Function get ($rss _url) & nbsp

if ($rss _url !=  "")  

//Create a  
$dir if the directory does not exist  =   RSS; 
if (!is_dir ($dir))  

mkdir ($dir,  0666); 
}&nb Sp
//  Create a unique name  
$file  = md5 ($rss _url); 
$path  =  "$dir/$file. xml"  ; 
//Copy feeds to local server  
copy ($rss _url,  "$path"); 
return  $path; 

In order to access the methods in the PHP class, you need to have a request file to act as an interface to the class, which is exactly the file we are requesting. This file first verifies a password variable from the request query, or returns a message that specifies that the requester is not an authorized user, or a path that points to the RSS feed, which is replicated to the local server after processing by the request method. To make a response to an RSS feed, you need to include the RSS object and instantiate it, and you need to activate the request method by using the URL of the requested feed as an argument:
Copy Code code as follows:

if ($password = = "MyPassword")
Require_once (' classes/rss.class.php ');
$rss = new RSS ();
echo $rss->get ($request);
echo "You are an unauthorized user";

Get/post combined with Ajax
For post requests, we first need to create the request object. If you don't have the experience to create the request object, you can read my article "How to use AJAX" or simply study the sample source code in this article. Once the request object is created, you can call the Sendfeed method and pass the URL created by the form:
Copy Code code as follows:

function Sendfeed (URL) {
Post.onreadystatechange = SendRequest; ("POST", url, True);
Post.send (URL);
Once the response from the PHP object is received and loaded correctly, another request is made to the local file that corresponds to the response. In this case, Post.responsetext provides us with the path to the new file:
function SendRequest () {
if (Checkreadystate (POST)) {
Request = Createrequestobject ();
Request.onreadystatechange = Onresponse; ("Get", Post.responsetext, True);
Request.send (NULL);

Analysis response
Because of the difference between RSS feeds, analyzing the response is challenging. Some contain images with headings and description nodes, while others do not. So, when we analyze feedback, we need to do a little checking to see if it includes an image. If it includes an image, we can, along with the title and link for the feed, display the image in the image div tag:
Copy Code code as follows:

var _logo = "";
var _title = response.getelementsbytagname (' title ') [0];
var _link = response.getelementsbytagname (' link ') [0];;
_logo + + "<a href= '" + _link + "' target= ' _blank ' >" + _title + "</a><br/>";
if (Checkfortag (response.getelementsbytagname (' image ') [0])
var _url = response.getelementsbytagname (' url ') [0];
_logo + = "<br/> '
document.getElementById (' logo '). InnerHTML = _logo;

Not only do we have to examine each image to show it, we also need to check it when traversing all the items in the feed. Because if there is an image, all the other headings and linked node indexes will not work correctly. Therefore, when the image label is found, we should adjust the index of the caption and link nodes by adding an index value (+1) to each traversal:
Copy Code code as follows:

if (Checkfortag (response.getelementsbytagname (' image ') [0]) "" i>0) {
var _title=response.getelementsbytagname (' title ') [I+1];
var _link=response.getelementsbytagname (' link ') [I+1];
var _title =response.getelementsbytagname (' title ') [I];
var _link = response.getelementsbytagname (' link ') [I];
You can use the Checkfortag method to check for specific tags:
function Checkfortag (tag) {
if (tag!= undefined) {
return true;
return false;

There are a number of possibilities for the analysis of feeds. For example, you can assign an item to a category and make the category fold so that users can choose what they want to see. As an example, I use dates to categorize items-this can be done by interpreting whether the pubdate for a particular item differs from the pubdate of the previous item and displaying a new date accordingly:
Copy Code code as follows:

if (i>1) {
var previouspubdate = response.getelementsbytagname (' pubdate ') [I-1];
if (pubdate!= previouspubdate | | previouspubdate = = undefined) {
_copy + = "<div id= ' detail ' >" + pubdate + "</div>}
_copy + + "<a href=\" javascript:showdetails (' + i + "); \" > "+ _title +" </a><br/><br/> ";
document.getElementById (' Copy '). InnerHTML + = _copy;

Note that the last part of the above is the ShowDetails method, which is used to show details when a user selects a particular item from a feed. This method has an argument (item index value) that is used to discover the index of the details node in the feed:
Copy Code code as follows:

function ShowDetails (index) {
document.getElementById (' Details '). InnerHTML = response.getelementsbytagname (' description ') [index].;
Use AJAX to send a query string to a server-side script and retrieve a custom response based on that string, which is possible for any web developer. In this way, your next Web application will be full of new possibilities.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.