The Storyteller

RSS Feed Mashup + Twitter = Yummy!

April 24, 2009 · 42 Comments

if you want to get all tech news update (or php news, did i forget to say python news or web 2/3/x news??) in one place, what could be better than a twitter account or a RSS feed reader. If you have a RSS feed aggregator, its plain and simple. But if you choose the other one (I mean Twitter) you have to be something more than a dumbass, as you have to create it by your own- lol!

so let me be something more than a “dumbass” today and show you how did i do it. i choose my all time best tool “php” for it. added some toppings with an external rss mashup builder and finally served the dish with twitter api. lets see what was the difficult part in it

goal:
you will provide a set of rss feed urls, then your application will create a mashed up feed with them (all in one place, sorted in ascending order by date), and publish the latest feed titles since last time update.

challenges
0. building a mashup with rss feed
1. keeping track of last time update and separate items which are new
3. post them to twitter
4. setting up cron to run it periodically

getting hand dirty
step 1: creating a rss feed mashup
so lets build a mashup of your favorite rss feed urls. you can make use of yahoo pipes for this or take help of any other web based mashup service. for this one, i experimented with the one available at xfruits.com. go there, open an account and add your feed urls. xfruit will give you a single feedurl which will deliver the mashed up content, sortedn in ascending order by date. so this part is done.

[update]
I tried with Xfruit but it doesn’t work well, most of the time it is down – and their update frequency is slow. so i build the mashup with yahoo pipes. here is the source
picture-24

after making a mashup of techcrunch, phpdeveloper, insidefacebook, ajaxian and honeytechblog my final mashed up feed url (via yahoo pipes)is http://pipes.yahoo.com/pipes/pipe.run?_id=bDfi0Pww3hGhpiLVPm7D0g&_render=rss

step 2: coding your little franky, the frankenstein
well, this code makes use of a tinyurl API to shorten the url of each feed story, SimpleXML to parse the RSS feed and extract stories and story-links from it, a text file to keep track of last updated content and twitter API to post them to twitter. here they come one by one.

class.tinyurl.php

< ?php
    /**
     * shorten any url with the help of tinyurl API
     *
     */

class TinyUrl
{
    static function getTinyUrl($url)
    {
        $tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url={$url}");
        return $tinyurl;
    }
}
?>

class.cachemanager.php

< ?php
/**
 * keeps track of updated items since last execute
 *
 */
class CacheManager
{
    private $lastHash;
    function __construct()
    {
        $this->lastHash = file_get_contents("hash.txt");
    }

    function getLashHash()
    {
        return $this->lastHash;
    }

    function setLastHash($hash)
    {
        $this->lastHash = $hash;
        file_put_contents("hash.txt",$hash);
    }
}
?>

class.twitter.php

< ?php
/**
 * update user's status in twitter
 *
 */
class Twitter
{
    private $username;
    private $password;
    function __construct($username, $password)
    {
        $this->username = $username;
        $this->password = $password;
    }
    function publishMessage($message)
    {
        try{
            $tweetUrl = "http://{$this->username}:{$this->password}@www.twitter.com/statuses/update.xml";
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $tweetUrl);
            curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, "status={$message}");
            $result = curl_exec($curl);
            //print_r($result);
        }
        catch(Exception $e)
        {
            //print_r($e);
            error_log($e->getMessage());
        }
    }
}
?>

now the most interesting part, to make use of all your objects and to cook them properly. here is the code of index.php

index.php

< ?php
include_once("class.cachemanager.php");
include_once("class.tinyurl.php");
include_once("class.twitter.php");
$twitter = new Twitter("username","password");
$cm = new CacheManager();
$lastHash = $cm->getLashHash();
$firstHash= "";
$feedUrl = "http://pipes.yahoo.com/pipes/pipe.run?_id=bDfi0Pww3hGhpiLVPm7D0g&_render=rss";
$rss = new SimpleXMLElement($feedUrl,LIBXML_NOCDATA, true);
$feedcount =  count($rss->channel->item)-1;
$items = array();
/**
 * process elements to get a list of items to post in twitter
 * also set a check point so that items are not double posted
 */
for($i=0;$i< =$feedcount;$i++)
{
    $title = $rss->channel->item[$i]->title;
    $link = $rss->channel->item[$i]->link;
    //echo "{$title}<br />{$link}<hr />";
    if($i==0) $firstHash = md5($title);
    $hash = md5($title);
    if($lastHash!=$hash)
    {
        $shortlink = TinyUrl::getTinyUrl($link);
        $items[] = array("title"=>$title,"link"=>$shortlink);
    }
    else
    break;
}
/**
 * set the checkpoint
 */
$cm->setLastHash($firstHash);
/**
 * post to twitter
 */
$items = array_reverse($items);
foreach ($items as $item)
{
    $message = "{$item['title']} - {$item['link']}";
    $twitter->publishMessage($message);
    echo $message."<br />";
}
echo "Whoa, Done Finally!";
?>

so you are done coding it. now set it as a cron job (you can use http://www.setcronjob.com if you are looking for a free one) from your cpanel. you are done.

You can check my twitter news updater at http://twitter.com/techupdater

Categories: PHP
Tagged:

42 responses so far ↓

  • Lenin // April 24, 2009 at 9:03 pm | Reply

    Just eased my exploration with Twitter.. thanks :P

    http://twitter.com/nine_L

  • TRIVUz // April 24, 2009 at 9:10 pm | Reply

    Boss… ghuman kemne ato buddhi loiya?

    BIGGG THANKS for this tricks :-D

  • ferdhie // April 24, 2009 at 9:31 pm | Reply

    sweet code, with a little mods can be used with plurk or FB ;)

  • Afruj // April 24, 2009 at 9:34 pm | Reply

    Thanks for the excellent job. it will help me a lot….

  • Md. Shoriful Islam Ronju // April 24, 2009 at 9:34 pm | Reply

    Cool tips. Apnar matha niya gobeshona kora dorkar.

  • Ishtiaque Ahmed // April 24, 2009 at 9:38 pm | Reply

    Great Work… as always. Thanks Hasin bhai! Just recently I started to use twitterfox. Now I can take full advantage of it by adding all my RSS feeds to twitter with this code. Whole world will be waiting for me on my firefox :)

  • Ehab // April 24, 2009 at 9:45 pm | Reply

    :)

  • ranacse05 // April 24, 2009 at 10:08 pm | Reply

    Thanks a lot . :D i was looking for this !

  • TaeWoo // April 24, 2009 at 10:14 pm | Reply

    this is similar to this: http://richardxthripp.thripp.com/tweet-this

  • shoeb // April 24, 2009 at 10:17 pm | Reply

    Cool!

  • hasin // April 24, 2009 at 10:18 pm | Reply

    @TaeWoo – that is really similar! thanks for the link – i didnt know abt that one.

  • Lenin // April 24, 2009 at 10:35 pm | Reply

    @TaeWoo : I have been using Tweet this but that has basic difference to this one.
    1. That’s WP plugin.
    2. Doesn’t use cronjob.
    3. Dont automatically post to tweeter.
    4. That is just an aid to the Blog visitors to be able to Tweet a liked post easily.
    5. This one aggregates RSS feeds and automatically posts to ONE single Tweeter Account.
    :)

  • Anupom Syam // April 24, 2009 at 10:53 pm | Reply

    nice trick! liked it. thanks for sharing. :)

  • Arafat Rahman // April 24, 2009 at 11:03 pm | Reply

    wow!
    Thanks for the post.

  • azzam sheikh // April 24, 2009 at 11:10 pm | Reply

    What about the restriction of the number of feeds that are sent? You do not want to bombard people with too many in one time.

  • Rayhan chowdhury // April 24, 2009 at 11:26 pm | Reply

    it’s definitely a great job, it’s really a new idea! to me.

    I am wondering if everyone start using ur code, we may be flooded by feed update, instead I am thinking to follow your http://twitter.com/techupdater

    thanks,

  • azzam sheikh // April 24, 2009 at 11:53 pm | Reply

    Excuse my ignorance but do I update password in index.php or class.twitter.php or both

  • hasin // April 25, 2009 at 12:41 am | Reply

    hi azzam, please update only in index.php :)

  • bayezid // April 25, 2009 at 1:14 am | Reply

    i faced a problem after running the code….

    the problem shows me that…Maximum execution time of 30 seconds exceeded …please suggest me

  • Hussain M Elius // April 25, 2009 at 1:45 am | Reply

    errr… twitterfeed anyone? http://twitterfeed.com

  • Nurul Ferdous // April 25, 2009 at 4:04 am | Reply

    Nice work :) You saved lots of time :P

    Thanks.

  • azzam sheikh // April 25, 2009 at 10:20 pm | Reply

    I am going with twitterfeed.com, it makes it all that easier

  • hasin // April 25, 2009 at 10:22 pm | Reply

    @Azzam – u r most welcome :)

  • Kowser // April 25, 2009 at 10:52 pm | Reply

    i use google reader actually. its more handy to me.
    dont forget take a try. however thanks for sharing your idea

  • azzam sheikh // April 25, 2009 at 11:47 pm | Reply

    I must say that it is handy since it delivers the feeds from the web and not from any other tool i.e ‘twitterfeed’, makes it look organic and naturally.
    Too many that look as if they are from RSS can be off putting.

    I suggest Hasin that a) Allow feeds to be sent on a timed basis 30 min, 1 hr, 4 hour, 24 hour, etc.
    b) they number of post submitted per tweet i.e. 5, 10, 15, 20, etc.

    that would be awesome

  • azzam sheikh // April 25, 2009 at 11:49 pm | Reply

    @kowser, I also use google reader with the greasemonkey/userscript for twitter. Works a treat with tinyurl. The fact that you send only the ones you have read manually ensures that you are only sending what you have read and confirmed what is good for your readers.

  • Mahmud Ahsan // April 26, 2009 at 10:04 pm | Reply

    awesome post. thanks hasin vai for this nice tips and tricks. :)

  • Wood Door // April 30, 2009 at 6:42 pm | Reply

    Very useful. Thanks for the nice article.

  • shahid // May 2, 2009 at 8:34 pm | Reply

    excellent OOP example for feed!
    oneker darooon kaje ashbe!

  • Lipna // May 9, 2009 at 9:52 pm | Reply

    Came to your site after longgg time, looks like missed a lot of fun :)
    I have been looking for the exact thing you posted(RSS Feed)! Thanks a lot Hasin.
    Am planning to sit for the Zend certifcate soon, any suggestion on that? Or do you already have a post for that I can look into?
    Once again! Thanks for all EXCELLENT posts!

  • Pete // May 11, 2009 at 4:33 am | Reply

    Please excuse my ingorance I am new to this. I have edited the index.php line 5 $twitter with my username and password. I’ve uploaded the files above to a dir on my server. When I run http://www.mydomain.com/bot/index.php the page shows me the text of my index.php file incuding my password. Please help. I have set this up in dreamhost cronjob as well but I nothing seems to work. Thanks in advance for you help.

  • Pete // May 11, 2009 at 7:02 am | Reply

    I have the cronjob executing the index.php file that I uploaded to a directory with the rest of the files but now my email notifier tells me:

    sh: 20: command not found

    Also if i browse to the index.php file in my browser it’s still showing me the text of the .php file in my browser.

  • RSS Feed Mashing + All Official Google Updates = In Single Feed Url | Sakib Mahmud — aka Googlememe — on Blogging, Social Networking, WordPress, Web Desing and Developement // May 11, 2009 at 5:49 pm | Reply

    [...] Inspired by RSS Feed Mashup + Twitter = Yummy! [...]

  • Chris // May 16, 2009 at 11:46 pm | Reply

    @Pete: In all the PHP files listed above, There is a space between < and ?php, so remove the space and Try.

  • Chris // May 24, 2009 at 7:55 am | Reply

    The code is working fine as along as there is no special characters in the item title.

    If the item title has any spl char, only the partial text of the item title ( until it hit the spl char) is updating to Twitter.

    Can you please look into this. Thanks.

  • Chris // May 24, 2009 at 9:01 am | Reply

    i mean characters like & < > "

  • Chris // May 24, 2009 at 9:52 am | Reply

    added a new line

    $message = urlencode($message);

    before

    $twitter->publishMessage($message);

    working fine for the above mentioned special character issues.

    Thanks

  • Shaikh Sonny Aman // May 25, 2009 at 4:37 pm | Reply

    Khub e kajer jinish!! Great idea and implementation :)

  • TechBytes » Blog Archive » RSS Feed to Twitter // June 17, 2009 at 7:21 pm | Reply

    [...] me so I started looking at alternatives and found this great post about how to do this via PHPRead RSS Feed Mashup + Twitter = Yummy!  Related PostsNo Related Post No Comments Read [...]

  • Gautam Kishore // June 18, 2009 at 8:25 pm | Reply

    Try FeedMingle http://feedmingle.com instead of yahoo pipes or xfruits. It is much easier and performs great.

  • Michael // June 20, 2009 at 8:44 am | Reply

    Amazing Script! I had one question:

    1. It currently says “posted from web” when posted to twitter – would you know how to change the text of that like twitterfeed or ping.fm do?

  • gnuboss // August 4, 2009 at 2:22 pm | Reply

    Very cool tutorial, I’m definitely going to take this and try to create a few little implementations. Very handy stuff indeed.

Leave a Comment