Include Twitter Data on your Website

Every application I build now is littered with various types of functionality that links them into different social network. If you’re reading this post it’s unlikely I’ll have to educate you on the merits of plugging your website into the social lives of your readers.

What follows is some code that will help you integrate twitter data into your website in a more meaningful way than simply including just a ‘retweet’ button.

Twitter Data on your Website

Twitter make an XML file available for each visible Twitter profile with various pieces of useful data… have a look at my profile data here. Since it’s an XML file, we can easily parse it and extract the information for use in our own applications.

I’m in the process of building a large number of websites that syndicates podcasts and I wanted to include a small Twitter profile box attached to every author’s page. Although very much in development, this is an image of what I’m rendering on a ‘profile page’ for each podcast.

It’s basically a simple box with some information extracted from the XML data referenced above. Of course, I could use more data and add a follow button – and I may end up doing just that – but it serves as a basic example of what you’ll accomplish with the very simple code below.

To use the data, you’ll have to extract it into a more meaningful format.

<?php
$sXML = new SimpleXMLElement('http://twitter.com/users/show.xml?screen_name=martykhoury', NULL, TRUE);
// TRUE specifies that data is a path or URL to an XML document instead of string data.
?>

SimpleXMLElement returns an object representing data.

Once we extract the elements of the XML data, we can print the object array simply so you have a feel for data that’s returned.

<?php
echo "<pre>";
print_r($sXML);
echo "</pre>";
?>

The variable $sXML is now an object with all the XML tags being attributes. To retrieve the any element you’ll simply access it in PHP’s object form. For example, here’s what you’ll use to extract certain elements:

<?php
$screen_name = $sXML->screen_name;
$location = $sXML->location;
$description = $sXML->description;
$followers_count = $sXML->followers_count;
$favourites_count = $sXML->favourites_count;
$friends_count = $sXML->friends_count;
$text = $sXML->status->text;
?>

… and so on.

Simple!

In my example above, I’ve parsed usernames, hashtags and URL‘s in the most recent tweet ($sXML->status->text) so they become clickable links. You can do that with the following.

<?php
// Make handles links
$text = preg_replace('#@([\\d\\w]+)#', '$0', $text);
// Make hashtags links
$text = preg_replace('/#([\\d\\w]+)/', '$0', $text);
?>

Of course, you’ll want to store the XML values into a database or flat file for a defined period of time to avoided repeated requests to Twitter.

A BETTER way of determining the number of times your URL has been retweeted

A couple of weeks ago, I showed you how to find the number of times your URL had been tweeted to Twitter using the TweetMeme API. Since I’ve been using it, I’ve found that it’s relatively unreliable and not nearly as accurate as obtaining the same data from Twitter (obviously). I had been using Twitter data and TweetMeme data on the same site meaning that there was a clear discrepancy when both sources happened to be rendered on the same page.

As an example, a link to one of my podcasts indicates 58 retweets via TweetMeme and 73 via Twitter. Not good.

Using Twitter’s API (with JSON), information retrived is far more accurate.


From Wikipedia, JSON (an acronym for JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for most languages.


The code

<?php
function tweetcount($url)
{
 $twitterjson = "http://urls.api.twitter.com/1/urls/count.json?url=%s";
 $fileData = file_get_contents(sprintf($twitterjson, $url));
 $json = json_decode($fileData, true); // true will be converted into associative array
 unset($fileData); // free memory
  return $json['count'];
}

$url = "http://www.flightpodcast.com/episode-6-john-bartels-qantas-qf30";
$twitcount = tweetcount($url);

echo  "Count: $twitcount";
// Will return (at the time of writing) 73
?>

PHP’s json_decode function is what’s used to covert the encoded string into a PHP variable. When set to TRUE (as in the above example), returned objects will be converted into associative arrays.

How about Facebook?

If you’re subscribed to my mailing list I’ve just sent you some free code that I intend to sell as a stand-alone package. It won’t be made available on this website. Having said that, I will post some general Facebook tools over coming weeks.


As always, if you have any problems or questions, please email me or leave a comment below.


First Name:
Your Email Address:
 


If you liked this article, you may also like:

  1. Determine the Relationship between two Twitter Users
  2. Why You Should NEVER Post Your Email to Twitter
  3. Count the Number of Shares to Facebook, Twitter, LinkedIn & Google Plus
  4. Twitter using CURL via their API
  5. Add a Facebook Follow/Subscribe Button to Your WordPress Website with Shortcode
About Marty

is a passionate web developer from Sydney, Australia. He owns about 600 websites and makes a healthy living from working the web. As a day job, he works as a pilot for an international airline. Follow Marty on Twitter or Google+.

Comments

  1. but how can you get a list of all your tweets?
    i see that in the status->text variable it holds the last submitted tweet only.

  2. Can this be used to extract location API data as well?

    • Good question — and I assume you mean tweet specific lat/long coordinates or “posted from” details? I don’t think so… but I’ll have to check. I’ve used it before but I can’t recall where I got the info. I’ll get to it in a few days. If you find your answer before I do, please let me know.

Trackbacks

  1. […] how to render that data on your screen in a small text box. I’ve posted about Twitter counts before in isolation; this post expands upon the same […]

Please leave a comment or question!

*