资料库 ☆ 华陌网
完整版 »
Building a Generic RSS Class With PHP
Building a Generic RSS Class With PHP
(0 篇回复 468 浏览)
This is a printable version of "Building a Generic RSS Class With PHP". For the complete online version, please visit http://www.devarticles.com/content.php?articleId=238 ________________________________________ Page 1: Introduction It seems that every site provides an RSS XML feed these days -? even we do. But what is an RSS XML feed, why would you want to create one, and how the heck do you create one? Well, in this article I'll attempt to answer all 3 questions for you, the intermediate PHP developer. In this article you will learn what RSS XML is and how to generate your own RSS XML file from a class that we will build in PHP. This class will connect to a database, grab the appropriate fields, and split out a nice RSS compatible XML file that you can share. To implement the class that we will create, you need at least PHP v4.1 installed. Note that you don't need any sort of XML support enabled -- we will simply be using mysql_xxx functions and joining some strings together. You will also need access to a MySQL database, which is where we will get the content to build our RSS XML data. I will assume that you have an intermedia knowledge of PHP, basic knowledge of XML, and no knowledge of the RSS standard. Page 2: What is RSS and How Does It Relate to XML? RSS stands for Rich Site Summary, and is an XML format that allows any Webmaster to share his news, articles, diary entries or whatever with other web sites. If you could consider MySQL as your permanent data store, then think of RSS as your business card for your web site. RSS is in use by all of the big players on the Internet, including but not limited to SlashDot, CNN, ZDNet, Salon and Internet.com. RSS XML is generated as plain text, and each RSS XML file is called a channel, so SlashDot has a channel, ZDNet has a channel, etc. The RSS specification started at version 0.91 in June 2000. It progressed to version 0.92 in December 2000, and now it's at version 2.0 ? although I prefer to stick with the 0.91 spec. There will be subsequent versions, however they will just be clarifications to the specification, not changes to the RSS format. In terms of a relationship to XML, RSS is simply a strict format that you must generate your XML into. It defines a set of tags that your content must fit into. If you're familiar with XML, then here’s how a typical RSS story looks:
My first article
This is my first article, I hope you like it.
http://www.devarticles.com/my_first_article.php
Each story in an RSS XML file is used to represent one article, one news headline, one diary entry, one recipe, etc. You can have up to 15 item blocks in your RSS XML file, however the less you have, the quicker the XML file is to parse for data. As you can see in our example above, each story is bound by
and
tags and has a title, description and link. An RSS XML file actually contains more content than a couple of
tags, and we will now take a look at the syntax of a complete RSS XML file. RSS XML Syntax RSS files allow you to syndicate your content into one file, which other webmasters can grab, parse and display on their web site ?- this is one of the best ways to drive instant traffic to your web site for little to no cost. In order for other webmasters to be able to use your RSS XML file, it needs to adhere to the correct syntax. All RSS files are based on XML, and look similar -? if not identical ?- to a normal XML file (accept for a few more element tags). To start with, our RSS file needs an XML version decleration tag: Next up, we can specify a DTD (document type definition), which will be used to make sure our RSS file conforms to its syntax. Netscape invented the RSS spec, so we use their DTD: We now need an RSS tag, which is the root element for our entire document. This tag simply looks like this:
As mentioned earlier, an RSS file is called a channel -? a syndication if you like ?- for a web site. We use a channel tag to include metadata about our RSS feed. The channel tag looks like this:
It can include the following elements: ? Title: The name of your RSS channel. ? Description: The description of your RSS channel. ? Link: A link to your web site's home page. ? Language: A language encoding attribute, which signifies how your RSS file is encoded. We don't need to worry about this attribute, and can just use en-us, which means our RSS file is encoded in U.S. English. Your channel tag can also include an image tag, which specifies the details and location to an image representing your site/channel. This image tag can include the following elements: ? Title: A name for your image. Used if the person parsing your RSS XML file wants an ALT tag for your image. ? URL: The URL to your image. ? Link: Where your image should link (preferably your home page). Here's how a channel tag might look for one web site:
My Sample Channel
http://www.mysite.com
My sample RSS channel
en-us
Following the channel tag, you can optionally include an image tag:
My Sample Image
http://www.mysite.com/mylogo.gif
http://www.mysite.com
The channel and image tags compose the "header" of our RSS XML file. The body of our RSS XML file is composed of several stories (item tags) that we discussed earlier, and might look something like this:
My first article
This is my first article, I hope you like it.
http://www.devarticles.com/my_first_article.php
My second article
This is my second article, I hope you like it.
http://www.devarticles.com/my_second_article.php
Lastly, the root tag is closed, like this:
And that's all there is to creating a basic RSS XML file! You can include other attributes such as owner details, copyright details, etc, but I've left these out because they are optional ?- I also wanted to keep this explanation as simple as possible. To see the full RSS XML 0.91 spec, click here. Before we move on, here's a complete RSS XML file (as displayed here):
UT Web Central Spotlights
http://www.utexas.edu/spotlight/
Spotlighted items on Web central and other pages
UT Austin
http://www.utexas.edu/graphics/star_with_ut.gif
http://www.utexas.edu/
New UT Austin Travel Program
http://www.utexas.edu/business/travel/travelchanges.html
Annual Enrollment 2000
http://www.utexas.edu/admin/ohr/irg/enroll/
Note: To prove that this is valid RSS XML, you can try validating it here. Page 3: Building Our PHP Class OOP makes life easier, there's no doubt about that. Programming with objects instead of functions and normal variables is quicker and is also more fun, too. If you're not familiar with OOP in PHP, then have a quick glance over David’s article by clicking here. We're going to build a class that will automatically generate a 100% RSS-compliant XML string for us. With this class, you will be able to share and syndicate your site's content and brag to all of your friends that you're down with the new trends in the world of XML. Let's start by creating a simple MySQL database, where we will store some fictional articles. Drop to the MySQL command window and run the following commands: create database rssDB; use rssDB; create table myArticles ( articleId int auto_increment primary key, title varchar(50), summary varchar(250), content text, unique id(articleId) ); We've just created a database and a simple table that will hold some articles. Remember that each item tag in our RSS XML file needs a title, description and link. The title, summary and articleId fields will be useful for this later on. We now need some articles. Run the following commands at your MySQL console to add some records to our myArticles table: insert into myArticles values (0, '1st Article', 'This is the summary of my first article', 'This is the body of my first article'); insert into myArticles values (0, '2nd Article', 'This is the summary of my second article', 'This is the body of my second article'); insert into myArticles values (0, '3rd Article', 'This is the summary of my third article', 'This is the body of my third article'); Now, let's start to create our class file. We will build on this code as we go, and a complete version is available in the support material for this article on the last page: class myRSS { // Create our channel variables var $channelTitle; var $channelLink; var $channelDesc; // Create our image variables var $imageTitle; var $imageLink; var $imageURL; We start by creating our class and calling it myRSS. We also setup 6 class-scoped variables to hold the details that will be used to build our channel and image tags later. Our class will be very simple, and will contain 2 functions: function checkValues() This function will make sure that appropriate values have been set for variables such as the channel's title, link and description, as well as the image details. function GetRSS($dbServer, $dbUser, $dbPass, $dbName, $tableName, $titleFieldName, $descFieldName, $linkFieldName, $linkTemplate) This function is a little more complex. It accepts your MySQL database details, table details and field details and builds an RSS XML string, which it returns. Let's start by looking at the checkValues function: function checkValues() { // Make sure all channel and image values are set if($this->channelTitle == "") die("Please specify a channel title"); if(ereg("$http://", $this->channelLink) == false) die("Please specify a channel link"); if($this->channelDesc == "") die("Please specify a channel description"); if($this->imageTitle == "") die("Please specify an image title"); if(ereg("$http://", $this->imageLink) == false) die("Please specify an image link"); if(ereg("$http://", $this->imageURL) == false) die("Please specify an image URL"); } The checkValues function uses some simple string comparison operators and some regular expressions to make sure class variables aren't empty, and that URL's for the image location, etc are prefixed with http://. This function is called from the GetRSS function, which is the main function of our application. Before we look at the GetRSS function, let's look at how we call our class, assuming that it's complete and all functions are setup. From a new file called test.php, we could use the following code: include("class.myRSS.php"); // Instantiate the myRSS class $myRSS = new myRSS; $myRSS->channelTitle = "My sample channel"; $myRSS->channelLink = "http://www.mysite.com"; $myRSS->channelDesc = "My sample RSS XML channel"; $myRSS->imageTitle = "My sample channel"; $myRSS->imageLink = "http://www.mysite.com/mylogo.gif"; $myRSS->imageURL = "http://www.mysite.com"; // Get the RSS data $rssData = $myRSS->GetRSS("localhost", "admin", "password", "rssDB", "myArticles", "title", "summary", "articleId", "http://www.mysite.com/articles/{linkId}/"); // Output the generated RSS XML header("Content-type: text/xml"); echo $rssData; There's nothing fancy about this code. We start by setting the appropriate values for the channel and image attributes, as discussed earlier. We then call the GetRSS function to grab our RSS XML and set a header type to tell the browser we're outputting XML instead of plain text. Before we look at the GetRSS function, here's a sneak peak of the XML output in IE 6.0: Page 4: The GetRSS Function The GetRSS function of our myRSS class uses string concatenation (joining) to build and return a string that contains XML data, generated from other variables in the class and also the records in our MySQL database, which we created earlier. The GetRSS function accepts 9 compulsory parameters: ? $dbServer: The IP/name of your MySQL database server, e.g. localhost. ? $dbUser: Your MySQL username, e.g. admin. ? $dbPass: Your MySQL password, e.g. mypass. ? $dbName: The name of your MySQL database. In our case this is rssDB. ? $tableName: The table from where records will be extracted. In our case this will be myArticles. ? $titleFieldName: The name of the MySQL field in our table which will be used as the title element in each item tag. In our case this will be title. ? $descFieldName: The name of the MySQL field in our table which will be used as the description element in each item tag. In our case this will be summary. ? $linkFieldName: The name of the MySQL field in our table which will be used to build a link to this article. In our case this will be articleId. ? $linkTemplate: A string in which the value {linkId} will be replaced with the value from the $linkFieldName field in our MySQL table. In our case we’ve used http://www.mysite.com/articles/{linkId}/, meaning that links will appear in our RSS XML feed as http://www.mysite.com/articles/45/ for example. GetRSS starts by calling the checkValues function of our class to make sure all channel and image variables have the correct values: // Connect to the database, generate the RSS XML and return it function GetRSS($dbServer, $dbUser, $dbPass, $dbName, $tableName, $titleFieldName, $descFieldName, $linkFieldName, $linkTemplate) { // Make sure all channel/image values have been set $this->checkValues(); Next, we build the header, channel and image tags from the class variables: $rssValue = "\r\n"; $rssValue .= "\r\n"; $rssValue .= "
\r\n"; // Build the channel tag $rssValue .= "
\r\n"; $rssValue .= "
" . $this->channelTitle . "
\r\n"; $rssValue .= "
" . $this->channelLink . "\r\n"; $rssValue .= "
" . $this->channelDesc . "
\r\n"; $rssValue .= "
en-us
\r\n"; $rssValue .= "
\r\n"; // Build the image tag $rssValue .= "
\r\n"; $rssValue .= "
" . $this->imageTitle . "
\r\n"; $rssValue .= "
" . $this->imageURL . "
\r\n"; $rssValue .= "
" . $this->imageLink . "\r\n"; $rssValue .= "
\r\n"; At this point the header of our RSS XML file is built, and stored safely in a variable called $rssValue. GetRSS now needs to connect to our MySQL database, grab each record in the specified table and turn them into item tags. We start by connecting the our MySQL database, and making sure the specified table exists by using the mysql_list_tables function: // Connect to the database and build the
tags $svrConn = @mysql_connect($dbServer, $dbUser, $dbPass) or die("Couldn't connect to database"); $dbConn = @mysql_select_db($dbName, $svrConn) or die("Couldn't select database"); // Make sure the table exists $tableExists = false; $tResult = mysql_list_tables($dbName); while($tRow = mysql_fetch_row($tResult)) { if(strtolower($tableName) == strtolower($tRow[0])) { $tableExists = true; break; } } if(!$tableExists) die("Table $tableName doesn't exist in the database!"); If all is well, then we create a MySQL query to grab the top 15 records in the database, ordered by the linkID field (remember that a channel can contain up to 15 items): $rResult = mysql_query("select $titleFieldName, $descFieldName, $linkFieldName from $tableName order by $linkFieldName asc limit 15") or die("An error occured while retrieving records: " . mysql_error()); As you can see, we substitute the values passed as parameters directly into the query as both table and field names. This makes our query 100% dynamic, and most importantly, generic ?- it can be used to rip an RSS XML file from any MySQL database where title, description and link fields exist. Next, we start a loop, grabbing the values from each MySQL record and appending them to the $rssValue variable as item tags: // The records were retrieved OK, let's start building the item tags while($rRow = mysql_fetch_array($rResult)) { $rssValue .= "
\r\n"; $rssValue .= "
" . $rRow[$titleFieldName] . "
\r\n"; $rssValue .= "
" . $rRow[$descFieldName] . "
\r\n"; $rssValue .= "
" . str_replace("{linkId}", $rRow[$linkFieldName], $linkTemplate) . "\r\n"; $rssValue .= "
\r\n"; } Notice this line in the code above: $rssValue .= "
" . str_replace("{linkId}", $rRow[$linkFieldName], $linkTemplate) . "\r\n"; What this code does, is replace the {linkId} part of the $linkTemplate variable with the ID from the article in our database. To top things off, we close the RSS tag and return the $rssValue to the caller of the function: // Add the closing rss tag and return the value $rssValue .= "
\r\n"; return $rssValue; All wallah! We have 1 generic PHP RSS XML generating class that can be used to convert any database into a real-time RSS-compatible XML syndication! Page 5: Testing Our Class Testing our class is easy. It should be separated into its own file, class.myRSS.php. You should use PHP to include this file and output the value from the GetRSS function. Once you’ve done this, any other Webmaster can grab and parse your RSS XML feed to display your headlines on their site, and you can also submit the link to your RSS file to RSS listings to drive an insane amount of traffic back to your site. Here's a quick example. Save it as rss.php in your root directory on your web server, along with class.myRSS.php and modify it as you need to: include("class.myRSS.php"); // Instantiate the myRSS class $myRSS = new myRSS; $myRSS->channelTitle = "My sample channel"; $myRSS->channelLink = "http://www.mysite.com"; $myRSS->channelDesc = "My sample RSS XML channel"; $myRSS->imageTitle = "My sample channel"; $myRSS->imageLink = "http://www.mysite.com/mylogo.gif"; $myRSS->imageURL = "http://www.mysite.com"; // Get the RSS data $rssData = $myRSS->GetRSS("localhost", "admin", "password", "rssDB", "myArticles", "title", "summary", "articleId", "http://www.mysite.com/articles/{linkId}/"); // Output the generated RSS XML header("Content-type: text/xml"); echo $rssData; Page 6: Conclusion In this article we've seen just how easy it is to get the power of XML working for us by using PHP and MySQL. You no longer have to wonder what RSS XML is -? you can start playing with it TODAY, getting more traffic to your web site in the process! If you need any help with this article or would like to discuss/present your implementation of our RSS XML class, then make sure you go to the forum thread for this article. ________________________________________ For more great programming articles, please visit http://www.devarticles.com. If you have an opinion or question about this article, then please post it at the devArticles developer forum, which is located at http://www.devarticles.com/forum
Powered by
flymote.com 华陌网
©
华陌
* archiver
* SE *