How to Generate Feed Using Php (Atom 1.0 and RSS 2.0 Compatible) - Code-Tips.com - Web Development, Programming, SEO

Sunday, August 14, 2011

How to Generate Feed Using Php (Atom 1.0 and RSS 2.0 Compatible)

In this tutorial, I demonstrate how to generate a feed using Php that can be displayed from a website in multiple formats, including Atom 1.0 and RSS 2.0.  I will be using functionality from the Php FeedWriter class library to generate the feed, which is available for free at http://phpFeedWriter.webmasterhub.net/.

I have broken up the process below into separate components, and provided additional information to help you learn each aspect of creating the feed using Php.  A download of the completed script written in this tutorial is also provided if required.

Summary

  • Prepare your feed script/page - Instantiate a (Php) FeedWriter Class Object
  • Add additional (Channel) data to the feed
  • Add Items to the Feed
  • Get the specified feed output format
  • (Optional) Set the “Content” element of each feed item as type “HTML”
  • Output the Feed XML
  • (Optional) Writing to a file / Caching Feed Content

Prepare your feed script/page - Instantiate a (Php) FeedWriter Class Object

  1. Download the latest version of the Php feedWriter Class library (free)
  1. Extract the package to a new directory on your web server that supports Php.  
For the purpose of this example,  have copied the Php FeedWriter class files to a "feed/" sub-folder.
  1. Create a new file called "feed.php".  
This file will be used to serve the feed content, so must be accessible from your website.
  1. Paste the following code into the file.


/* Example Feed using Php FeedWriter http://phpFeedWriter.webmasterhub.net/ 
 * Example feed: http://phpfeedwriter.webmasterhub.net/samples/1/feed.php
 *
 * View the tutorial: http://www.code-tips.com/2011/08/how-to-generate-feed-using-php-atom-10.html 
 */
require_once('feed/FeedWriter.php');

//Block 1 ----------------------------------------------
//Title if the feed
$feed_title = 'Example Feed using Php FeedWriter';

//Feed Link.  This should be a URL to the website, or blog that content displayed in the feed is from.
$feed_link = 'http://www.code-tips.com/';

//A short description of the feed.
$feed_description = 'This is an exmaple feed created as part of the tutorial on code-tips.com for generating RSS / Atom feeds using Php.';

//Instantiate the FeedWriter class
$feedWriter = new FeedWriter(
	$feed_title, 	//Feed Title
	$feed_description, //Feed Description
	$feed_link, //Feed Link
	6, //indent
	true, //Use CDATA
	null, //encoding
	true //enable validation
	);

//Enable debug
$feedWriter->debug = true;


  1. In the code you have just pasted, replace the example title, description and feed link with your own.
At this point, the an object has been created from the FeedWriter class, which will now be used to add items and later display the feed.  The additional options included when instantiating an object from the FeedWriter class control how the feed is outputted.  
  • When developing the feed, you should enable validation to ensure that you have included enough information in the feed for it to be valid in each output format.  
  • The option to enable CDATA will result in character data (CDATA) tags being written where text content is included in the feed.  This may be required depending on the type of information you are adding to the feed, and how you would like it to be displayed.  
  • It is also possible to set the character encoding for the feed output when constructing the FeedWriter object.  In this example, I have set this to null so that it uses the default (EN-US).  
  • Enabling validation ( $feedWriter->debug = true; ) will also assist when developing the feed, as additional information is provided when a feed is not valid instead of a generic message.  The information includes the specific elements  in the feed schema  used to output the feed that were missing required information.  Links are also provided to the relevant documentation on the Php FeedWriter website.
    For more information about using the FeedWriter class constructor, see the online documentation: FeedWriter Constructor.

     

    Add additional (Channel) data to the feed

    There is a range of additional meta information that can be added to a feed, including dates (Published/Modified), author details, refresh intervals and categories.  This information is used by feed readers and aggregators when updating and displaying your feed.  Some feed formats require additional information to be included in the feed to be valid.
    Many of the functions provided by the FeedWriter class can be used to add information to the feed as well as individual items in the feed.  When these functions are called before items have been added to the feed, the data is associated with the feed itself.  After items have been added, the data passed to one of these functions will be added to the item most recently added to the feed.
    1. Paste the lines of code in the following steps one after another, after the first code block included in the file.  Change the values as necessary.
    • Set an image for the feed (Required for some RSS formats)
      $feedWriter->set_image('WebmasterHub.net', 'http://www.webmasterhub.net/img/logo.jpg','http://www.webmasterhub.net/');
      
      • Specify the language of the feed content (Required for some formats)
        $feedWriter->set_language('EN-US');
        
        • Specify the date that content in the feed was last updated (Required for Atom 1.0)
          $feedWriter->set_date('2011-08-12T00:00:00Z',DATE_UPDATED);
          
          • Include contact details of the feed author (Required for Atom 1.0)
            $feedWriter->set_author(null, 'Daniel','http://www.code-tips.com/');
            
            • Set the “Self Link”, which is the URL to the feed. (Required for Atom 1.0)
              $feedWriter->set_selfLink('http://phpfeedwriter.webmasterhub.net/samples/1/feed.php');
              
              Refer to the FeedWriter Class Documentation for a list of functions that can be called to add additional information to the feed.

               

              Add Items to the Feed

              Items are added to the feed simply by calling the add_item() function.  Different information is required depending on the specified output format, so it is good practice to include all, or as much information as possible.  Some formats require that at least one of the title, description/content or link be included.
              For the purpose of this example, I have added a number of static/hard coded items to an array.  In reality, building a feed that retrieves information from a database or other dynamic source is a more common and practical solution.  The “items” array is created for the purpose of demonstrating how to generate a feed using Php.  You should replace this array with a similar array or source of information from your website.   Using an associative array of a database query result is probably the easiest way to put the code in this example into practical use.
              1. Paste the following code block into the file, after the previous code



              //Block 3 ----------------------------------------------
              //Create/Retrieve array containing data for the sample items 
              //this array should be replaced with your database query result array or similar
              
              //## Section 3.1 - Items Array
              $items = Array();
              $items[] = Array( 
              	//Example Item 1
              	'item_title' => 'Php FeedWriter Example Feed: Item',
              	'item_content' => 'This is an example item. 
               This HTML should be rendered when the feed is displayed in a browser or reader that supports HTML output...',
              	'item_link' => 'http://www.code-tips.com/link_to_post.html',
              	'item_published' => '2011-08-12T00:00:00Z',
              	'item_updated' => '2011-08-12T00:00:00Z');
              $items[] = Array( 
              	//Example Item 2
              	'item_title' => 'Php FeedWriter Example Feed: Item 2',
              	'item_link' => 'http://phpfeedwriter.webmasterhub.net/',
              	'item_published' => '2011-08-12T00:00:00Z',
              	'item_updated' => '2011-08-12T00:00:00Z');
              
              
              //## Section 3.2 - Loop through the items array, add items to the feed
              foreach($items as $item)
              {
              	//Get the title, content, link for the current item if supplied.
              	if(isset($item['item_title']))
              		$item_title = $item['item_title'];
              	else
              		$item_title = null;
              		
              	if(isset($item['item_content']))
              		$item_content = $item['item_content'];
              	else
              		$item_content = null;
              		
              	if(isset($item['item_link']))
              		$item_link = $item['item_link'];
              	else
              		$item_link = null;
              	
              	//Add the current item to the feed
              	$feedWriter->add_item($item_title, $item_content, $item_link);
              	
              	//Add additional data to the current item if available
              	if(isset($item['item_updated']))
              		$feedWriter->set_date($item['item_updated'], DATE_UPDATED);
              		
              	if(isset($item['item_published']))
              		$feedWriter->set_date($item['item_published'], DATE_PUBLISHED);
              }
              


              1. Set the items array (section 1 of code block 3) to your data source, or leave the example array in place to continue and test the feed.
              2. Update the Loop component (section 2 of code block 3) so that the array key values match your items array, or replace with your own values as required.
              Refer to the FeedWriter Class Documentation for a list of functions that can be called to add additional information to feed items.

               

              Get the specified feed output format

              The “feed.php” script that is being written in this example will take one query string (GET) parameter ”format”, that indicates which format to use when displaying the feed.  If none is supplied, or the value supplied does not correspond to one of the supported formats, the default format (Atom 1.0) will be used.  The formats that are supported by Php FeedWriter are: Atom 1.0, RSS 2.0, RSS 1.0, RSS 0.92 and RSS 0.91.  
              1. Paste the following code into your php file on an empty line after the code block added in the previous step.

              //Block 4 ----------------------------------------------
              //Get the format to display in, 
              //set to RSS 2.0 as default or if format is not found
              $format = Atom_1;
              if(isset($_GET['format']) && $_GET['format'] != null)
              {
              	foreach($feedWriter->getFeedFormats() as $curFormat)
              	{
              		if($curFormat[0] == $_GET['format'])
              			$format = $curFormat[1];
              	}
              }
              

              We are retrieving the feed format at this point to allow the output to be modified to allow HTML to be rendered when the feed is displayed.  This can be done at any point in the script prior to calling the getXML() function to generate and display the feed.  getXML() also has a default format if non is supplied, which is RSS 2.0.
              The loops through an array containing each of the supported format, and sets the output format for the feed if one matches the value passed to the “format” query string parameter.
              The default format can be changed by changing the ATOM_1 constant to another format. ($format = ATOM_1;).  For a list of constants used by the class, see Php FeedWriter Constants.

               

              (Optional) Set the “Content” element of each feed item as type “HTML”

              1. Paste the following code into your Php file on an empty line after the code from the previous step.
              //Block 5 ----------------------------------------------
              //Set the item body/content output type to html for the selected output format
              $feedWriter->set_feedConstruct($format);
              $feedWriter->feed_construct->construct['itemContent']['type'] = 'html'; 
              
              This code adjusts the “Feed Construct” for the specified output format so that the “itemContent” element is set to type HTML.  The Feed Construct is a class the builds a representation of a feed schema for use when validating and outputting a feed using Php FeedWriter.  
              We first set the specific format using the set_feedConstruct() function.  Once set, each “construct” from the specified output format can be accessed and modified using the FeedConstruct class functionality (a “construct” represents a single element in the XML schema of a feed format).  The element/construct that we want to update is “itemContent”.  
              • For more information, and a full list of constructs for each format, see Predefined Feed Constructs.  
              • For a list of the abstracted values such as “itemContent” used to represent similar elements across multiple formats, see commonName Values.  

                 

                Output the Feed XML

                The feed is outputted using the getXML() function.  The format is passed to the getXML() function as a parameter, which defines the output format.  The value obtained earlier in the script will be passed to the function.
                When validation is enabled, the getXML() function will validate the feed before outputting the XML.  If the feed is not valid in the specified output format, a feed will be generated by Php FeedWriter containing information about why the feed was not valid.  When debug is enabled, additional information is included about the specific components that were not valid.  Both debug and validation can be disabled once you are happy with the feed to prevent this validation feed from displaying on a live website.
                1. Copy the following code into the file after the block added in the previous step
                //Block 6 ----------------------------------------------
                //Build and output the feed XML in the specified, or default format
                //--------------------------------
                echo $feedWriter->getXML($format);  
                

                 

                (Optional) Writing to a file / caching feed content

                It is also possible to write the output to a file for scenarios where the feed content should be cached, where the output file would be used to display the feed from your website instead of building the feed and generating the feed XML each time.
                To write the feed output to a file, use the code below.  Please ensure that you understand the security risks associated with allowing the web server to write files before attempting this on a public website.  The code below would replace the block added in step 12 that includes the call to the getXML() function.
                $feedWriter->writeToFile('filename.xml',$format);
                

                The Php FeedWriter website provides full documentation on the classes that make up the solution.  Sample feed scripts are also available to download from the site.


                View the feed created in this tutorial: Atom 1.0, RSS 2.0, RSS 1.0, RSS 0.92, RSS 0.91.

                Download the full Php script created in this tutorial.

                0 comments:

                Post a Comment