Using Your Recorded Feeds


The feeds have been found, cleaned, and prepared, then recorded. Now comes the time to use these feeds. The options are nearly endless; the goal here is merely to present a few attractive options.

Email Mailing List

Although having target individuals use feed aggregators themselves is the common practice, it may not always be appropriate. Many corporate environments maintain strict control over which applications are permissible on client PCs, or may not want to burden nontechnical staff with the task of installing and configuring a feed aggregator. This also presents a bandwidth advantage, because the feed is downloaded once by the server and then emailed to the appropriate staff members, rather than having each staff member in turn make use of the Internet connection to download the feed.

 <?php   include ("../common_db.php");   $subscribers = array();   array_push($subscribers, array('email' => "paul@example.com", 'format' => 1));   array_push($subscribers, array('email' => "joe@example.com", 'format' => 0)); 

For this example, recipients of the message are set initially in an array. If you have a large or dynamic set of recipients, this data could just as easily be pulled from a database.

   $query = "SELECT id, source, title, DATE_FORMAT(date,'%a, %d %b %Y %T EST') as     date, link, content FROM 03_feed_raw WHERE (NOW() - `date`) < 86400";   $updatedFeeds = getAssoc($query); 

Set the query to select all updates completed in the past day (60 seconds Mlti 60 minutes Mlti 24 hours = 86,400 seconds in a day). The date will be formatted nicely (Tue, 14 Dec 2004 17:19:32 EST).

   //Produce HTML Version   $htmlUpdate = "<html><body>";   foreach ($updatedFeeds as $item)   {     $htmlUpdate .= "<h3>{$item['title']}</h3>\r\n";     $htmlUpdate .= "<font size=-1>{$item['date']}</font>\r\n";     $htmlUpdate .= "<p>{$item['content']}<br>\r\n";     $htmlUpdate .= "<a href=\"{$item['link']}\"title=\" Full Story\">{$item['link']}</a></p>\r\n";     $htmlUpdate .= "<br><br>\r\n";   }   $htmlUpdate .= "<p>This email is sent as a service of example-corp. If you no longer wish to receive it, or wish to change subscription options please contact the help desk</p>";   $htmlUpdate .= "</body></html>\r\n";   //Produce Plain Text Version   $plainUpdate = strip_tags($htmlUpdate); 

Generate two different versions of the email, one for those who wish to receive (or are capable of receiving) an HTML formatted document, and one for those who would prefer a plain text version.

   $htmlHeaders  = "MIME-Version: 1.0\r\n";   $htmlHeaders .= "From: Daily Feed Updates <dailyfeed@example.com>\r\n";   $htmlHeaders .= "Content-type: text/html; charset=UTF-8\r\n";   $plainHeaders = "MIME-Version: 1.0\r\n";   $plainHeaders .= "From: Daily Feed Updates <dailyfeed@example.com>\r\n"; 

Generate headers for both types of email; note the Content-Type header added for the HTML formatted message.

   $error = "";   foreach($subscribers as $individual)   {     if($individual['format'] == 1)     {       if (!mail($individual['email'], "Daily Feeds", $htmlUpdate, $htmlHeaders))        {          $error .= "Error To:{$individual['email']}, Content: $htmlHeaders\n";        }     }else if ($individual['format'] == 0)     {        if (!mail($individual['email'], "Daily Feeds", $plainUpdate, $plainHeaders))        {          $error .= "Error To: {$individual['email']}, Content: $plainUpdate\n";        }     }   } 

Each recipient is iterated through, and a message is sent. If the mail() function returns an error, save that separately. Note that the mail() function will only return an error if it is unable to contact the MTA, any other possible problems with the message are ignored (for example, an invalid destination address). As such, it is likely that if one message fails to go through they all will.

   if (!($error == ""))   {     $error = "Messages could not be delivered because the MTA could not be contacted\r\n" . $error;     file_put_contents("/tmp/feederrors.txt", $error);     echo "$error";   } ?> 

If errors are encountered they are saved to a local file. Note that it would be pointless to attempt to email the error messages because it has already been determined that the MTA is unreachable. If the automated process used to call the script has a better way to contact a human operator, for example, page to console, and save file to specific web directory, and so on, it would make for an easy replacement. Generally speaking, when one major error has already been encountered it is good practice to first make an attempt to save information about the error in as simple a manner as possible (in other words, dump to a file or output to console), then try the more complicated methods such as paging.

This example uses PHP's mail function to transport the mail to the MTA. Each message that is sent will require a separate connection to the MTA, because the process is (for each function call) to connect, communicate, and disconnect. As an example, sending 100 messages to a local MTA from PHP took 216 seconds during testing.

If you are planning on sending a large amount of mail, say over 1,000 recipients, you may want to look into either directly connecting to the MTA with streams or, as mentioned earlier, using a dedicated piece of mailing list software.

On Page Widget

Generating a small on page widget (suitable for use in a sidebar, for example) should be rather trivial once you have recorded the feeds. These two short example functions should provide you with some ideas:

 function getStories($count, $source = "") {   $titleLength = 25;   $storyLength = 100;   if($source == "")   {     $query = "SELECT `title`, `content`, `link` FROM 03_feed_raw ORDER BY `date` DESC LIMIT $count";   }else   {      $query = "SELECT `title`, `content`, `link` FROM 03_feed_raw WHERE source = '$source' ORDER BY `date` DESC LIMIT $count";   }   echo $query;   $stories = getAssoc($query);   foreach($stories as &$story)   {     $story['title'] = substr(strip_tags($story['title']), 0, $titleLength);     $story['content'] = substr(strip_tags($story['content']), 0, $storyLength);     echo ".";   }   return $stories; } 

This function retrieves the most recent stories (up to the supplied maximum) either from any source, or optionally a specific source. It also strips all HTML tags from the elements in question and trims them down to a preset length. Note the use of the ampersand before $story in the foreach loop. It is important to remember that foreach, by default, works on a copy of the given array. The ampersand directs the loop to work directly with the array in question. This option is new to PHP5, so if a previous version is still in use, a different method of array iteration will need to be used.

You will note that the table name used in the previous several examples has been feed_raw — that's exactly what it contains, raw feed data. If you intend to use other formats of the data throughout your site (as is done in this example), it would be best for you to use multiple tables, one containing raw data, the others containing specifically formatted versions of that data for use elsewhere:

 function printWidget($count, $source = "") {  $stories = getStories($count, $source);  foreach($stories as $story)  {    echo "<a href=\"{$story['link']}\">{$story['title']}</a><br>\n";    echo "<p>{$story['content']}</p>\n";  } } 

Using the preceding function prints out the specified number of stories in a simple HTML format. Assuming some sort of stylesheet is inherited from the page in question, it actually works out rather well.

Note 

Notice that no validation was ever done to the $source variable. Keep that in mind while coding, you will need to ensure that it is specified by code, not by the user. For example, it could be populated either statically or from a generated array, where the user gives the index to select the desired element. It should not, however, be given directly by the user (or allowed to be given on a request URL) because it is vulnerable to a SQL Injection attack.

Customizable Portal Page

Using the preceding code, it is trivial to create a portal page that looks suspiciously like Slashdot or Netscape:

 <html> <head> <title>Example Portal Page</title> </head> <table width="100%" border="1"> <tr>   <th width="15%">Paul's Blog</th>   <th width="70%">Yahoo! Technology</th>   <th width="15%_>Chris's Blog</th> </tr> <tr valign="top">   <td><?php printWidget(3, "http://www.preinheimer.com/rss.php?version=2.0"); ?></td>   <td><?php printWidget(7, "http://rss.news.yahoo.com/rss/software"); ?></td>   <td><?php printWidget(3, "http://shiflett.org/rss"); ?></td> </tr> </table> </body> </html> 

Taking that code as a base, and with a little tweaking of the maximum length from getStories() earlier, you have a reasonable looking portal, as shown in Figure 3-4.

image from book
Figure 3-4

Improving the Portal Page

Naturally, there is always room for some improvement, so here are a couple of suggestions to get you going.

You could use cookies to allow users to select which elements they want to see and where. For example, add a few drop-downs to your existing user admin page to allow the users to select among your available feeds, and then display those feeds when they view the index page.

Use caching to reduce load. If the page is dynamically generated each time it is loaded, you may soon bring the server to its knees — plan ahead and cache content. In this context it probably makes the most sense to cache each feed you provide in a "nugget form" ready to be plugged into any page as required, and also cache the default page in its entirety because most users will probably not bother to change the defaults. Several caching methods are discussed in the next chapter.

Display the total number of items available from any particular feed. Underneath each feed provide a More option, indicating the number of additional items available from that feed. You may want to provide only current items (in other words, the last 10–25 depending on feed update frequency), or simply allow access to every item in your database.




Professional Web APIs with PHP. eBay, Google, PayPal, Amazon, FedEx, Plus Web Feeds
Professional Web APIs with PHP. eBay, Google, PayPal, Amazon, FedEx, Plus Web Feeds
ISBN: 764589547
EAN: N/A
Year: 2006
Pages: 130

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net