Populating sfSimpleBlogPlugin from RSS

posted 5th March 2008 21:03

Finally, I've moved my personal site to Symfony. I've been using the framework extensively professionally for a bit more than a year. I decided to use sfSimpleBlogPlugin to handle the blogging requirements on the site. I could have spent a while fiddling with databases to get the old data from my site off, but instead I decided to follow a different route by pulling all of my data from my old RSS feed.

Symfony provides the excellent sfFeed2Plugin for producing and parsing various feed formats. I used this outside of the controllers in a batch task to do import my old data in. Here is the code :

  <?php

  // set up a the symfony environment for batch 
  define('SF_ROOT_DIR',    realpath(dirname(__FILE__).'/..'));
  define('SF_APP',         'frontend');
  define('SF_ENVIRONMENT', 'prod');
  define('SF_DEBUG',       false);

  require_once(SF_ROOT_DIR. DIRECTORY_SEPARATOR.'apps' .DIRECTORY_SEPARATOR.SF_APP. DIRECTORY_SEPARATOR.'config'. DIRECTORY_SEPARATOR. 'config.php');

  sfContext::getInstance();

  // get the RSS
  $feed = sfFeedPeer::createFromWeb('http://www.markng.co.uk/rss.php?c=blog');

  // delete all posts in the posts table (remove this if not doing an initial import)
  sfSimpleBlogPostPeer::doDeleteAll();

  // get items from the feed and then loop through and save
  $items = $feed->getItems();
  foreach ($items as $key => $post) 
  {
    $importPost = new sfSimpleBlogPost();
    $importPost->setAuthorId(1);
    $importPost->setTitle($post->getTitle());
    $importPost->setStrippedTitle($post->getUniqueId());
    $importPost->setContent($post->getDescription());
    $importPost->setIsPublished(1);
    $importPost->setAllowComments(1);
    $importPost->setCreatedAt($post->getPubDate('U'));
    $importPost->setPublishedAt($post->getPubDate('U'));
    $importPost->save();
  }

If you were to use this, you may need to change the stripped titles to unique Id - I changed my old CMS slightly to output slugs as unique ID's so that it would be easy for me to do redirects for my old URL structure. I put this in the batch folder, and then ran it from the root of the project using :

  php batch/rss_import.php

« markng.co.uk