Create RSS aggregators using PHP and Ajax

Source: Internet
Author: User
Tags object http request include php language php class php and string access
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.

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:



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:
"Password=mypassword

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:



Enter a feed:





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:

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

   Attention

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:

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 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)
{
if ($rss _url!= "")
{
If no directory exists, create a
$dir = "RSS";
if (!is_dir ($dir))
{
mkdir ($dir, 0666);
}
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:

?
if ($password = = "MyPassword")
{
Require_once (' classes/rss.class.php ');
$rss = new RSS ();
echo $rss->get ($request);
}
Else
{
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:

function Sendfeed (URL) {
Post.onreadystatechange = SendRequest;
Post.open ("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;
Request.open ("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:

var _logo = "";
var _title = response.getelementsbytagname (' title ') [0].firstchild.data;
var _link = response.getelementsbytagname (' link ') [0].firstchild.data;;
_logo + + "
";
if (Checkfortag (response.getelementsbytagname (' image ') [0])
{
var _url = response.getelementsbytagname (' url ') [0].firstchild.data;
_logo + = "
"
}
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:

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 for specific tags:

function Checkfortag (tag) {
if (tag!= undefined) {
return true;
}
else{
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:

if (i>1) {
var previouspubdate = response.getelementsbytagname (' pubdate ') [I-1].firstchild.data;
}
if (pubdate!= previouspubdate | | previouspubdate = = undefined) {
_copy + = "
";
}
_copy + + " + _title +"

";
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:

function ShowDetails (index) {
document.getElementById (' Details '). InnerHTML = response.getelementsbytagname (' description ') [index]. Firstchild.data;
}

   Conclusions

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.

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.