Creating a simple news feed module (for display within static blocks)

Here I will explain how I implemented a simple news feed feature that can be used inside static blocks. Before creating this, I had a look, and only found a commercial offering for this, so I hope this is of use to other people. It also was a learning experience for me, as it is the first code I have done for Magento that utilises a custom template.

To save myself a little work, I took an off the shelf RSS and Atom feed parser called “Simplepie”. This might not have been the best choice as there are a couple of issues with it. Firstly it is reasonably large, and no doubt does a lot more than I require. Secondly, I had some problems getting it to work with Magento. This was due to simplepie having php4 compatibility, and because I like to run my php5 with E_STRICT error reporting, php complained. This however was a quick fix and I will cover that later. If anyone knows a modern, compact php5 rss/atom parser that is any good, please do let me know.

First let’s start then with simplepie, the modifications to make to it, and where to  install it. Paths referenced in these instructions should be considered relative to the Magento root folder.

Download the latest simplepie archive from the website (http://simplepie.org/). At the time of writing this is version 1.1.3. Unpack it somewhere. Create a folder in your Magento installation called lib/simplepie.

Copy the simplepie.inc and the idn folder (and any LICENCE.txt etc) to the magento/lib/simplepie folder. You should now have a folder structure similar to

lib/simplepie/
              LICENSE.txt
              simplepie.inc
              idn/
                  idna_convert.class.php
                  LICENCE
                  npdata.ser
                  ReadMe.txt

Now we will make some simple modifications to the simplepie.inc file (and also rename it to simplepie.class.php – this is just my own preference). Simplepie includes php4 compatibility that could cause problems running on php5 depending on your error reporting settings. The following sed commandline will correct this so simplepie will not cause errors and will ingrate with Magento on a PHP5 setup with E_STRICT error reporting.

sed -e "s/& new/ new/g" simplepie.inc >simplepie.class.php

After running this, you can remove the old simplepie.inc. There are some other things within the simplepie code that will also cause problems running in E_STRICT mode on php5, but we can work around this by changing the error reporting level in our module. I will explain this further on.

Our newsfeed module will be stored in app/code/local/Maglife/Newsfeeds. The Maglife folder is our module namespace, and the Newsfeeds is the name of the module. The structure here is as follows

app/code/local/Maglife/Newsfeeds/
                                 Block/
                                       View.php
                                 etc/
                                     config.xml

The file View.php contains the main module code, and the config.xml contains the module configuration, including version number, and class name.

File: app/code/local/Maglife/Newsfeeds/etc/config.xml
This file contains the module configuration including module version number and our module class.

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Maglife_Newsfeeds>
            <version>0.1.0</version>
        </Maglife_Newsfeeds>
    </modules>
    <global>
        <blocks>
            <Maglife_Newsfeeds>
                <class>Maglife_Newsfeeds_Block</class>
            </Maglife_Newsfeeds>
        </blocks>
    </global>
</config>

File: app/code/local/Maglife/Newsfeeds/Block/View.php

This file contain the main code for our module. Our module will also have a template file, that also contains some code, but the bulk of the work is done here, so that the template is kept as simple as possible.

Note that we include the idna_convert.class.php first, as otherwise there are issues with the class being autoloaded from the wrong location. As I mentioned earlier a more lightweight parser may well be better suited, or perhaps using simple_xml to parse the feed manually. You will also see in the class contructor we switch the php error reporting and then back in the destructor. This is to stop issues with simplepie and E_STRICT mode on php5.

This code is very simple, and could be extended further. When we utilise the Newsfeeds module from magento, we will pass in parameters for the feed url, the number of items to display and an optional title. The initFeed() call will set up and retrieve the feed from the feedurl parameter configured within our static block (covered later on).  I have three main calls. These are initFeed() that will be called from the start of the Newsfeed template (listed later),  a call getFeedCount to get the number of feed items to display (or return a default of 5), and getFeedTitle that will return the title of the feed (or a pre configured title passed from the static block). The initFeed call has some code to configure the cache folder. The Mage::getConfig()->createDirIfNotExists($cache_dir); call is used to create a folder in the magento/var/cache folder called “newsfeeds”. This relies on the /var/cache folder being writable by the web server process. This however should already be setup correctly on your magento installation.

<?php

require_once('simplepie/idn/idna_convert.class.php');
require_once('simplepie/simplepie.class.php');

class Maglife_Newsfeeds_Block_View extends Mage_Core_Block_Template {

    public $_feed;
    private $_old_reporting;

    public function __construct()
    {
        // simplepie is made for php4 and will report errors in E_STRICT mode
        $this->_error_reporting = error_reporting( error_reporting() & ~ E_STRICT );
        $this->_feed = new SimplePie();
    }

    public function __destruct()
    {
        // restore error reporting to previous setting
        error_reporting($this->_old_reporting);
    }

    public function initFeed()
    {
        $this->_feed->set_feed_url($this->getfeedurl());
        $var_dir = Mage::getConfig()->getTempVarDir();
        $cache_dir = $var_dir . '/cache/newsfeeds';
        Mage::getConfig()->createDirIfNotExists($cache_dir);
        $this->_feed->set_cache_location($cache_dir);
        $this->_feed->init();
        $this->_feed->handle_content_type();
    }

    public function getFeedCount()
    {
        // if there is a count attribute for our block, use that,
        // alternatively, use a default
        if ( $this->getcount() ) {
            return $this->getcount();
        } else {
            return 5;
        }
    }

    public function getFeedTitle()
    {
        // if there is a title attribute for our block, use that for the
        // heading, alternatively, use the title of the news feed
        if ( $this->gettitle() ) {
            return $this->gettitle();
        } else {
            return $this->_feed->get_title();
        }

    }

}

Now for the template that controls the display/look of the newsfeeds block. You may well want to change this. The template lives in app/design/frontend/interfacename/theme/template/newsfeeds. For the default interface and theme that Magento ships with this would be app/design/frontend/default/default/template/newsfeeds. If you are using a custom theme you will want to create the newsfeeds folder in the relevent theme/templates folder. You are not forced to use this template file and folder name, but if you change them, make sure you reference the template correctly from the static block (shown later). The design and classes used in this template fit well with the Magento “blank” theme. The Magento blank theme is a simple theme that is a good starting point for creation of your own.

File: app/design/frontend/default/default/template/newsfeeds/view.phtml
A simple piece of html and php. The first line calls our initFeed() function that retrieves the feed. We then get the title, and loop through the feed items (displaying them in an unnumbered list). The $this->_feed object is a feed object returned by simplepie, so the code below for getting the items, is the same as you would find in the simplepie documentation.

<?php $this->initFeed() ?>
<div class="block block-newsfeeds">
    <div class="block-title">
        <h2><?php echo $this->getFeedTitle() ?></h2>
    </div>
    <div class="block-content">
        <ul>
        <?php foreach ($this->_feed->get_items(0, $this->getFeedCount()) as $item) { ?>
            <li>
                <a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title() ?></a>
            </li>
        <?php } ?>
        </ul>
    </div>
</div>

This is the last of the files for our module. The only thing left to do, is to activate the module within Magento, and then utilise our module within a static block. To enable our module we must make a small configuration file in app/etc/modules

File: app/etc/modules/Maglife_All.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Maglife_Newsfeeds>
            <active>true</active>
            <codePool>local</codePool>
        </Maglife_Newsfeeds>
    </modules>
</config>

If you already have a Maglife_All.xml file (for example if you have used one of our earlier modules), then just add the <Maglife_Newsfeeds> section to the <modules> section of the xml.

Now, we are ready to try out the module.

Log into your Magento administration panel and navigate to the CMS/Static Blocks menu, and Add new Block. Enter the following information

  • Block Title: Newsfeeds
  • Identifier: newsfeeds
  • Store View: All Stores
  • Status: Enabled
  • Content: {{block type=”Maglife_Newsfeeds/View” template=”newsfeeds/view.phtml” feedurl=”http://news.google.com/news?ned=us&topic=h&output=atom” count=”5″}}

This tells Magento to use our custom block Maglife_Newsfeeds/View, with the template newsfeeds/view.phtml (or another template of your choice), along with the feedurl (for Google news – top stories). The count parameter is the number of items to display. There is also a title parameter that can be set to change the title in the displayed news block. If omitted as above it will use the title returned by the newsfeed.

Save this static block. We now want to make it display on the site. In this example we will make it display at the top right of the homepage. Navigate to CMS/Manage Pages on the administration panel and choose the Home page page that comes with the default magento install. Select the tab custom design. There should be a block of commented out XML. From here you can add layout XML to the homepage. Add the following XML to the bottom in the Layout Update XML textbox.

<reference name="right">
    <block type="cms/block" name="newsfeeds" before="-">
        <action method="setBlockId"><block_id>newsfeeds</block_id></action>
    </block>
</reference>

This tells Magento to display our static block at the top of the “right” section in the layout.

Now, hopefully, you should be able to navigate to your Magento home page and see a list of news items from Google news!

If you don’t I suggest turning on the debug logging from the Magento System/Configuration menu and checking for debug output  in var/logs/exception.log.

Please do let me know if you find any mistake/typos in this article. It is possible I may have forgotten a step or two. I hope this is of use to you, and at least gives some more ideas on how to work with Magento.

16 thoughts on “Creating a simple news feed module (for display within static blocks)”

  1. Wow – very thorough write-up. Thank you so much!

    It couldn’t be more perfect timing too – I was just looking for something like this. Google picks up these posts fast!

    Reply
  2. How do I place the feed on some place other than the “right” column?

    For example, I want to put it on my 1-Column homepage within a specific DIV. When I place the code you provided in the “Content” section of the CMS (instead of Custom Design), it just says “Newsfeed” where the feed should be.

    Reply
  3. if you want to just place it in the “content” section of the CMS, just use the code from the static block like

    <h1>Home Page</h1>
    {{block type=”Maglife_Newsfeeds/View” template=”newsfeeds/view.phtml” feedurl=”http://news.google.com/news?ned=us&topic=h&output=atom” count=”5″}}

    Reply
  4. The code allows you to pull in a feed from another site (for example BBC News) and display it within a block on your Magento website. This block will be indexed in the same way as other content on the page.

    Reply
    • This is exactly what I have been looking for! Can one add multiple feeds to a website? And if so how would that be done?

      Reply
      • Just use the {{block type=”Maglife_Newsfeeds/View” template=”newsfeeds/view.phtml” feedurl=”http://news.google.com/news?ned=us&topic=h&output=atom” count=”5″}} multiple times with different urls for different feeds.

        Reply
  5. Thanks again, that is what I figured but I always make sure to double check.

    IF for some reason one does not carry all of these steps out correctly could it possibly corrupt the structure of the site and stop it from being published on the web correctly?

    Never hurts to triple check lol

    Reply
    • That command does an equivalent of replacing “& new” with ” new” in the simplepie code. You could do the same on a text editor. I would suggest that you might consider getting someone else to implement this code for you if you are not comfortable or familiar with such things. I would also recommend you look at my earlier comment on this where I link to an alternative solution that is a fair amount simpler to implement, and has less resource requirements (it utilises the Zend framework that Magento already uses).

      Reply
  6. take the the xml layout code above that starts


    <reference name="right">
    <block type="cms/block" name="newsfeeds" before="-">

    and instead of putting it into the update xml you can put it into the main theme layout. go to app/design/frontend/default/default/ayout (for the case of the default theme)

    you can place it in one of the layouts there, or make a new one.

    Reply
  7. Hi

    The module looks great and easy to install..I followed the same as per your instructions.But the module is not appearing in the frontend.I could not understand the last step how to turn on the debugging output in the adminstration side.

    Reply
  8. can i write static block inside another static block..if no plz give me details why so

    static {
    ….
    ……………

    static {
    ……………………..
    }
    }

    Reply

Leave a comment