Create RSS aggregator with PHP and Ajax

Source: Internet
Author: User
Tags md5 encryption

[Guide] Imagine using a simple HTML file to send a request to a server script and receive a custom XML file based on the request, then display it to the user without refreshing the browser! The author will discuss with you how to combine PHP and Ajax technologies in common web applications to create real-time data transmission without refreshing the browser.

Although the PHP language is used in this article, please remember that any server language will work normally. To understand this article, I assume that you basically understand JavaScript, PHP, or a similar server-side language.

In this example, Ajax is used to send a request from an RSS feed to a custom PHP Object. This PHP Object copies the feed on the local server and returns this path. The request object receives the path, analyzes it, and displays the data to the user in HTML format. This sounds like it involves many steps. In fact, it consists of only four small files. Four small files are used to balance their specific strengths and make the processing of the entire system 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. This allows you to bypass the cross-origin restrictions imposed by xml http request objects. Later, I will explain how to create this custom PHP Object. But first, let's start with form creation.

Create a Request Form

The first thing you need to do is include JavaScript and any CSS files that you may want to use between your HTML head tags. I included a style table to implement the final layout of the aggregator and used a Javascript file to send requests and analyze the feeds:

<Link href = "CSS/layout.css" rel = "stylesheet" type = "text/CSS"/>

<SCRIPT src = "JS/request. js"> </SCRIPT>

Next, create a form that sends a request to an RSS feed you selected. The Form I created contains only one input field and one button for submitting the request. The query of this request is a string consisting of the feed input value and a password that will be verified on the server side. As an example, I use the following form:

"Password = mypassword

This code sends a request each time the page is loaded. Therefore, if the page is refreshed, the existing feed string in this input field will be requested during page loading. The following is an example of form data, along with some Div labels used to display specific nodes of the analyzed feed:

<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 = "20">

<Input type = "Submit" name = "Submit" value = "add feed">

</Form>

<Div id = "logo"> </div>

<HR/>

<Div id = "copy"> </div>

<Div id = "details"> </div>

</Body>

The three Div labels I created are logo, copy, and details. Each of them has an associated style in the layout style sheet. They will be used when we analyze the feeds, but we need to first be able to access the feeds we requested. 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, which creates a copy of the request feed on the local server so that it can be accessed by the XML HTTP request object we will create later. Typically, you cannot request a file across domains, which means that the file to be requested must be on the local server. This class is a way to solve cross-domain problems, because it creates a copy of the feed, this copy is requested on the local server and returns the local path to the feed, then it is accessed by the request object.

The only method in this class is a request method, which has only one parameter pointing to the requested RSS feed URL. Then, it checks whether a directory is located on the local server through the RSS name. If it does not exist, create a directory and set its permission mode to 0666, which means the directory can be read and written. When it is set to readable, the directory can be accessed later. When it is set to writable, you can write a copy of the feed to the directory on the local server:

// Create a directory if the directory does not exist

$ Dir = "RSS ";

If (! Is_dir ($ DIR ))

{Mkdir ($ dir, 0666 );

}

Note:On a Windows Server, pattern settings in PHP 4.2.0 and later are not required. However, if it exists, it will be ignored; therefore, I keep it for the project to be migrated to a Unix or Linux server.

Before copying a feed to this server, we need a unique file name. I used the MD5 encryption method for this complete URL to ensure that all the feed names are unique. With this new file name, it can connect a string describing the directory pointing to the file; this will be used when creating a copy of the feed:

// Create a unique name

$ File = MD5 ($ rss_url );

$ Path = "$ DIR/$ file. xml ";

You can create a copy of the file by referring to the defined path above and the original requested feed URL. Finally, return the path to the new file as a response to the request:

// Copy the feed to the local server

Copy ($ rss_url, "$ path ");

Return $ path;

Following is the small, yet powerful RSS class in its entirety:

<? PHP

Class RSS

{Function get ($ rss_url)

{

If ($ rss_url! = "")

{

// Create a directory if the directory does not exist

$ Dir = "RSS ";

If (! Is_dir ($ DIR ))

{

Mkdir ($ Dir, 0666 );

}

// Create a unique name

$ File = MD5 ($ rss_url );

$ Path = "$ DIR/$ file. xml ";

// Copy the feed to the local server

Copy ($ rss_url, "$ path ");

Return $ path;

}

}

}

?>

To access methods in this PHP class, a request file is required to act as an interface of this class, which is exactly the file we are requesting. This file first verifies a password variable queried from this request, or returns a message indicating that the requester is not an authorized user, you can also use the path pointing to the RSS feed (which is copied to the local server after being processed by the Request Method) to respond. In response to this RSS feed, you need to include this RSS object and instantiate it. You need to use the requested URL as a parameter to activate the request method:

<?

If ($ Password = "mypassword ")

{

Require_once ('classes/RSS. Class. php ');

$ RSS = New RSS ();

Echo $ RSS-> get ($ request );

}

Else

{

Echo "you are an unauthorized user ";

}

?>

Combination of get/post and Ajax

For post requests, we first need to create the request object. If you have no experience in creating request objects, you can read my article "How to Use Ajax" or simply study the sample source code in this article. Once this request object is created, you can call the sendfeed method and pass the URL created by the form:

Function sendfeed (URL ){

Post. onreadystatechange = sendrequest;

Post. Open ("Post", URL, true );

Post. Send (URL );

}

Once a response from a PHP Object is received and loaded correctly, another request is sent to the local file corresponding to the response. In this case, post. responsetext provides the path to the new file:

Function sendrequest (){

If (checkreadystate (post )){

Request = createrequestobject ();

Request. onreadystatechange = onresponse;

Request. Open ("get", post. responsetext, true );

Request. Send (null );

}

}

Analysis Response

Because of the differences between RSS feeds, analysis and response are challenging. Some images contain titles and description nodes, while others do not. Therefore, when analyzing feedback, we need to check whether it includes an image. If it includes an image, we can display the image in the image Div label together with the title and link of the feed:

VaR _ logo = "";

VaR _ Title = response. getelementsbytagname ('title') [0]. firstchild. Data;

VaR _ link = response. getelementsbytagname ('link') [0]. firstchild. Data ;;

_ Logo + = "<a href = '" + _ link + "'target =' _ blank '>" + _ title + "</a> <br/> ";

If (checkfortag (response. getelementsbytagname ('image') [0])

{

VaR _ url = response. getelementsbytagname ('url') [0]. firstchild. Data;

_ Logo + = " <br/>"

}

Document. getelementbyid ('logo '). innerhtml = _ logo;

We must not only check each image to display it, but also check it when traversing all the items in the feed. Because if an image exists, all other titles and link node indexes will not work properly. Therefore, when an image tag is found, we should adjust the index of the title and link node by adding the index value (+ 1) in each traversal:

If (checkfortag (response. getelementsbytagname ('image') [0]) "" I> 0 ){

VaR _ Title = response. getelementsbytagname ('title') [I + 1]. firstchild. Data;

VaR _ link = response. getelementsbytagname ('link') [I + 1]. firstchild. Data;

}

Else {

VaR _ Title = response. getelementsbytagname ('title') [I]. firstchild. Data;

VaR _ link = response. getelementsbytagname ('link') [I]. firstchild. Data;

}

You can use the checkfortag method to check whether a specific tag exists:

Function checkfortag (TAG ){

If (tag! = Undefined ){

Return true;

}

Else {

Return false;

}

}

There are many possibilities for feed analysis. For example, you can assign an item to a category that can be folded, so that users can select the content they want to watch. As an example, I use date to classify items-this can be achieved by translating whether the pubdate for a specific item is different from the pubdate of the previous item and displaying a new date accordingly:

If (I> 1 ){

VaR previouspubdate = response. getelementsbytagname ('pubdat') [I-1]. firstchild. Data;

}

If (pubdate! = Previouspubdate | previouspubdate = undefined ){

_ Copy + = "<Div id = 'detail'>" + pubdate + "</div> <HR Align = 'left' width = '000000'/> ";

}

_ Copy + = "<a href =" javascript: showdetails ('"+ I + "'); ">" + _ title + "</a> <br/> ";

Document. getelementbyid ('copy'). innerhtml + = _ copy;

Note that the last part is the showdetails method, which is used to display details when a user selects a specific item from a feed. This method has a parameter (item index value), which is used to find the index of the details node in the feed:

Function showdetails (INDEX ){

Document. getelementbyid ('details'). innerhtml = response. getelementsbytagname ('description') [Index]. firstchild. Data;

}

Conclusion

Use ajax to send a query string to a server script and retrieve a custom response based on the string. This is possible for any web developer. In this way, your next web application will be filled with new possibilities.

 

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: info-contact@alibabacloud.com 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.