Generate RSS Feeds

Introduction

This tutorial explains how to use OnpubAPI and Unversal Feed Generator to retrieve a section of articles created with Onpub and convert it to RSS. This is a quick and easy way to syndicate and share the content you create within Onpub.

Requirements

Getting Started

The first step is to include the required PHP classes:

<?php

include 'FeedWriter.php';
include 
'onpub/api/onpubapi.php';

?>

Next, create a connection to the Onpub Database (see this tutorial for more info) and construct the OnpubSections object:

<?php

$pdo = new PDO'mysql:host=localhost;dbname=test''test''test' );

$osections = new OnpubSections($pdo);

?>

The OnpubSections object represents a connection to the OnpubSections table in the Onpub database. We can now use this object to get the section and all its articles as follows:

<?php

$queryOptions = new OnpubQueryOptions();
$queryOptions->includeArticles true;
$queryOptions->orderBy 'created';
$queryOptions->order 'DESC';

$section $osections->get(1$queryOptions);
$articles $section->articles;

?>

The above code uses the OnpubQueryOptions to tell the database to return the articles in Section ID 1 ordered by the date they were created in descending order (i.e., newest articles first). You can change the section ID from 1 to the ID of any Onpub section you want to syndicate using this code.

We are now ready to generate the RSS feed using the data we just retrieved from the Onpub database:

<?php

$TestFeed = new FeedWriter(RSS2);

$TestFeed->setTitle('Onpubco Blog');
$TestFeed->setLink('http://onpubco.com/');
$TestFeed->setDescription('');

$TestFeed->setImage('Onpubco Blog','http://onpubco.com/','http://onpubco.com/images/onpubco.png');

$TestFeed->setChannelElement('language''en-us');
$TestFeed->setChannelElement('pubDate'date(DATE_RSStime()));

foreach ($articles as $article) {
  
$authors $article->authors;

  $newItem $TestFeed->createNewItem();

  
$newItem->setTitle($article->title);
  
$newItem->setLink('http://onpubco.com/tryonpub/template/index.php?sectionID=' $section->ID '&articleID=' $article->ID);

  
$newItem->setDate($article->getCreated()->format('c'));
  
$newItem->setDescription($article->content);

  if (
sizeof($authors)) {
    
$newItem->addElement('author'$authors[0]->displayAs);
  }

  
$TestFeed->addItem($newItem);
}

$TestFeed->genarateFeed();

?>

As you can see the above code uses the $section and $articles objects created above to help generate the contents of the RSS feed. The FeedWriter class does all the heavy lifting of actually generating the XML that makes up a valid RSS document.

This concludes the tutorial on how to create RSS feeds from content created within Onpub. Click the link below to download the full working PHP source code (includes comments) for this tutorial.

Tutorial Source Code

Comments

Feel free to comment on this article below. Any abusive/offensive material will be removed without notice.

blog comments powered by Disqus