Twitter Icon Logo
me@grafxflow

Written by me@grafxflow

12 Oct, 2012

1

3,089

PHP code for outputting twitter RSS feed

UPDATE: THIS SCRIPT NO LONGER WORKS DUE TO TWITTER DROPPING SUPPORT FOR RSS FEED! Read this new article about Adding a Twitter feed APP to WordPress.

Here is a PHP script for bringing in a twitter RSS feed to your website. It does repeat a few functions several times to check whether the twitter feed is empty/dead.

It allows you to:

  • Backup the RSS feed to your server as an xml file.
  • Schedule how often the backup is created.
  • Set the number of feeds to output.
<?php
class twitter_rss_feed
{
    public $url = 'https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=';
    public $filename = 'directory_for_file/your_twitter.xml'; // Make sure the directory already exists
    public $username = 'twitter_name';
    public $maxfeed = 2; // Limit amount of feeds shown
    public $maxfeedtime_difference = 5; // How often xml file is saved in minutes

    public function detect_if_feed_empty($tweets)
    {
        if ($tweets->channel->title && $tweets->channel->title != '') 
        {
            // Twitter RSS feed is NOT empty
            return true;
        } else {
            // Twitter RSS feed is empty
            return false;
        }
    }

    public function output_twitter_feed()
    {
        // Detect if the saved xml file exists
        if (file_exists($this->filename)) {

            // Check the files creation date/time against current date/time
            $to_time = strtotime(date ("F d Y H:i:s."));
            $from_time = strtotime(date ("F d Y H:i:s.", filemtime($this->filename)));

            // Check the file was created more than ($maxfeedtime_difference) minutes ago
            if (round(abs($to_time - $from_time) / 60,2) >= $this->maxfeedtime_difference)
            {
                // File is older so update the saved xml file
                // Read Twitter RSS Feed
                $xml = simplexml_load_file($this->url.$this->username);

                // Detect of Twitter feed isn't empty
                // Twitter maybe empty if you have accessed it more than 100 times over the last hour OR you have no tweets... so start creating some Tweets!
                if (twitter_rss_feed::detect_if_feed_empty($xml) == true)
                {
                    // Save new xml file
                    $xml->asXml($this->filename);   
                }
            }
        } 
        else 
        {
            // Detected the saved xml file doesn't exist
            // Create new xml file usually first time of running php class/function
            // Read Twitter RSS Feed
            $xml = simplexml_load_file($this->url.$this->username);

            // Detect of Twitter feed is empty
            // Theoretically this should never be empty since it will be the first time of creating an xml and reading the RSS feed, OR you have no tweets... so start creating some Tweets!
            if (twitter_rss_feed::detect_if_feed_empty($xml) == true)
            {
                // Save a new xml file
                $xml->asXml($this->filename);
            }
        }
        // Finally
        // Create the array from RSS feed
        $mytweets = twitter_rss_feed::fetch_tweets();
        // Output the Twitter RSS feed as results
        twitter_rss_feed::twitter_results($mytweets);
    }

    public function fetch_tweets() 
    {
        // Load the xml file using simplexml
        $tweets = simplexml_load_file($this->filename);

        // Initialise empty array to store tweets
        $tweet_array = array();
        foreach ($tweets->channel->item as $tweet) 
        {
            // Loop to limit the number of tweets.
            if ($this->maxfeed == 0) 
            {
                break;
            } else {
                // Fetch the tweet itself
                $twit = $tweet->description;

                // Remove the preceding 'username: '
                $twit = substr(strstr($twit, ': '), 2, strlen($twit));  
                $twit = preg_replace('/http:\/\/([a-z0-9_\.\-\+\&\!\#\~\/,]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $twit);

                // Convert usernames (@) into links 
                $twit = preg_replace('(@([a-zA-Z0-9_]+))', '<a href="http://www.twitter.com/\1">\0</a>', $twit);

                // Convert hash tags (#) to links 
                $twit = preg_replace('/(^|s)#(w+)/', '1<a href="http://search.twitter.com/search?q=%232">#2</a>', $twit); 

                // Specifically for non-English tweets, converts UTF-8 into ISO-8859-1
                $twit = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $twit);

                // Get the date it was posted
                $pubdate = strtotime($tweet->pubDate);

                // Customize this to your liking for the date output
                $propertime = gmdate('j M, Y', $pubdate);

                // Store tweet and time into the array
                $tweet_item = array(
                'desc' => $twit,
                'date' => $propertime,
                );
                array_push($tweet_array, $tweet_item);

                $this->maxfeed--;
            }
        }
        // Return array
        return $tweet_array;
    }

    // Decided to do as seperate function incase you want to change the output layout //
    public function twitter_results($mytweets)
    {
        // Output the Twitter results //
        echo '<div id="twitter_feed_holder">';
        echo '<h1>'.$this->username.' @ twitter feed...</h1>';

        foreach ($mytweets as $k => $v) 
        {
            echo '<p>'.$v['desc'].' <span>'.$v['date'].'</span></p>';
        }

        echo '</div>';  
    }

}
?>

And use this to call the function:

$twitter_output = new twitter_rss_feed;
$twitter_output->output_twitter_feed();

Add comment

1 Response

    me@grafxflow
    18 Oct 2012

    If you are having any issues with the script, check the following:


    • Have you changed all the relevant details at the top of the script, like the twitter username, plus created the folder for saving the file?

    • The read and write permissions of the folder containing the xml file.

    • You may have reached your twitter feed limit for the hour before using the script.

Smart Search

133 Following
50 Followers

me@grafxflow

Hull, United Kingdom

I am a Full-stack Developer who also started delving into the world of UX/UI Design a few years back. I blog and tweet to hopefully share a little bit of knowledge that can help others around the web. Thanks for stopping by!

Follow