Code _php instances that use PHP and Ajax to create RSS aggregators

Source: Internet
Author: User
Imagine using a simple HTML file to send a request to a server-side script, receive a custom XML file based on that request, and then display it to the user with little need to refresh the browser! The author will work with you to explore how to federate PHP and Ajax Technologies 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 article, 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, parses it, and displays the data as HTML to the user. This may sound a lot of steps, but it only consists of 4 small files. 4 small files are used to balance their particular strengths and make the entire system extremely efficient.
I think some readers might ask why you want to create a copy of the feed on the local server instead of simply analyzing the most primitive feeds. 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 form creation.
Create a form that makes the request
 
The first thing you need to do is to include the JavaScript and any CSS files you might want to use between your HTML head tags. I included a model table to implement the final layout of the aggregator and use a JavaScript file to make requests and perform feed analysis:


Next, create a form that makes a request for an RSS feed of your choice. The form I created only includes an input field and a button that submits the request. The query for the request is a string consisting of the feed input value and a password word that will be verified on the server side; As an example, I use 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 domain will be requested when the page loads. The following is an example of a form data, along with some div tags that show the specific nodes of the analyzed feeds:
Copy CodeThe code is as follows:








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. We will use them when we analyze feeds, but first we 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 created a small RSS class with PHP that creates a copy of the request feed on the local server so it can be accessed by the XML HTTP request object that we will 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 solve 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 to see if a directory is located on the local server by the name of the RSS feed. If it does not exist, create one and set its permission mode to 0666, which means that the directory is readable and writable. When it is set to be readable, the directory can be accessed later, and when it is set to writable, a copy of the feed can be written to the directory on the local server:
Copy CodeThe code is as follows:
If no directory exists, create a
$dir = "RSS";
if (!is_dir ($dir))
{
mkdir ($dir, 0666);
}

Attention
On a Windows machine, the schema settings are not required for PHP 4.2.0 and above. However, if it exists, it will be ignored, so I keep it in case the project is migrated to a UNIX or Linux server.
Before copying the feed to the server, we need a unique file name. I used the MD5 encryption method for this full URL to ensure that the names of all feeds are unique. With this new file name, it can connect a string that describes the directory that points to the file, which will be used when creating a copy of the feed:
Copy CodeThe code is as follows:
Create a unique naming
$file =md5 ($rss _url);
$path = "$dir/$file. xml";

By using the reference that is defined in the path above and to the URL of the original requested feed, we can now create a copy of the file. Finally, the path is returned to the new file as a response to the request:
Copy CodeThe code is 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)
{
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, a request file is required to serve 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 requestor is not an authorized user, or responds with a path to the RSS feed that is copied to the local server after processing by the request method. In order to respond to an RSS feed, you need to include this RSS object and instantiate it, and you need to activate the request method by using the URL of the requested feed as a parameter:
Copy CodeThe code is as follows:
if ($password = = "MyPassword")
{
Require_once (' classes/rss.class.php ');
$rss = new RSS ();
echo $rss->get ($request);
}
Else
{
echo "You is an unauthorized user";
}
?>

Get/post combined with Ajax
For a POST request, we first need to create the request object. If you don't have the experience of creating a Request object, you can read my article "How to use AJAX" or simply look at the sample source code for this article. Once the request object is created, you can call the Sendfeed method and pass the URL created by the form:
Copy CodeThe code is as follows:
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 corresponding 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);
}
}

Analyze the response
Because of the difference between RSS feeds, analyzing responses can be challenging. Some contain images that contain headings and descriptive 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 feed's title and link, display the image in an image div tag:
Copy CodeThe code is as follows:
var _logo = "";
var _title = response.getelementsbytagname (' title ') [0].firstchild.data;
var _link = response.getelementsbytagname (' link ') [0].firstchild.data;;
_logo + = "+ _title +"
";
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 we traverse all the items in the feed. Because if there is an image, all additional headings and link node indexes will not work correctly. Therefore, when an image label is found, we should adjust the index of the caption and link nodes by increasing the index value (+1) in each iteration:
Copy CodeThe code is as follows:
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 the existence of a specific label:
function Checkfortag (tag) {
if (tag! = undefined) {
return true;
}
else{
return false;
}
}

There are a number of possibilities for feed analysis. For example, you can assign items 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 achieved by translating whether the pubdate for a particular item differs from the previous item's pubdate and displays a new date accordingly:
Copy CodeThe code is as follows:
if (i>1) {
var previouspubdate = response.getelementsbytagname (' pubDate ') [I-1].firstchild.data;
}
if (pubDate! = Previouspubdate | | previouspubdate = = undefined) {
_copy + = "+ PubDate +" ";
}
_copy + = "+ _title +"

";
document.getElementById (' Copy '). InnerHTML + = _copy;

Note that the last part of the above is the ShowDetails method, which is used to display details when a user selects a particular item from a feed. This method has a parameter (item index value) that is used to discover the index of the details node in the feed:
Copy CodeThe code is as follows:
function ShowDetails (index) {
document.getElementById (' Details '). InnerHTML = response.getelementsbytagname (' description ') [index]. Firstchild.data;
}
Conclusion
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 to implement. 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.