PHP snippets to interact with Twitter

Twitter is an awesome tool for website owners, and you should definitely integrate it into your website if you want to attract more traffic and new visitors. Today, let's take a look at some PHP snippets to interact with Twitter.

Get number of Twitter followers

Have you seen my blog sidebar? I display the number of followers I have in full text. This is actually pretty easy to do. The first thing you need is this function:

function get_followers($twitter_id){
	if (preg_match('/followers_count>(.*)</',$xml,$match)!=0) {
		$tw['count'] = $match[1];

	return $tw['count'];

Once you have the function, you can call it as shown below:

$nb =  get_followers('phpsnippets');
echo "PHP Snippets already have ".$nb." followers!";

» Credit:

Get latest Twitter status

Using PHP and cURL, it is pretty easy to get the status of a specific user. Once you have it, what about displaying it on your blog, like I do in WPRecipes footer?

function get_status($twitter_id, $hyperlinks = true) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, "$twitter_id.xml?count=1");
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    $src = curl_exec($c);
    preg_match('/<text>(.*)<\/text>/', $src, $m);
    $status = htmlentities($m[1]);
    if( $hyperlinks ) $status = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", '<a href="%5C%22%5C%5C0%5C%22">\\0</a>', $status);

The function is extremely easy to use:

echo get_status('catswhocode');


Link to update status, without encoding problems

Many websites and blogs show you how to create a link to Twitter that will update your status. But unfortunely, most websites don’t explain what you need to do in order to avoid encoding problems of spaces and special characters.

<a href=" Hi Jean, how are you?">Tweet!</a>

So, where’s the change? Pretty simple: Just note that I havent linked to, but to, without the www.

A working example can be seen on my company website:

Get number of retweets for a specific page

Most bloggers are using the Tweetmeme widget to display the number of retweets of their posts. Did you know that Tweetmeme also has an API you can use to get how many times a specific url has been retweeted?

The following function will get the number of RT’s of the url passed as a parameter:

function tweetCount($url) {
    $content = file_get_contents("".$url);
    $element = new SimpleXmlElement($content);
    $retweets = $element->story->url_count;
        return $retweets;
    } else {
        return 0;

Using the function is easy, as you can expect:

echo tweetCount('');

Note that the Twitter API also provide a way to get the number of retweets. See for example.


Testing friendship between two users

If you want to know if a specific user is following you (or someone else) you have to use the Twitter API. This snippet will echo true if the two users specified on lines 18 and 19 are friends. It will return false otherwise.

/* makes the request */
function make_request($url) {
	$ch = curl_init();
	$result = curl_exec($ch);
	return $result;

/* gets the match */
function get_match($regex,$content) {
	return $matches[1];

/* persons to test */
$person1 = 'phpsnippets';
$person2 = 'catswhocode';

/* send request to twitter */
$url = '';
$format = 'xml';

/* check */
$persons12 = make_request($url.'.'.$format.'?user_a='.$person1.'&user_b='.$person2);
$result = get_match('/<friends>(.*)<\/friends>/isU',$persons12);
echo $result; // returns "true" or "false"


Shorten urls for Twitter

As you know if you’re a Twitter user, you can’t post messages which are longer than 140 characters. To avoid this problem, you have to use an url shortener. There’s lots of different url shorteners on the internet. is one of them, it doesn’t produce the shortest urls but what I really love it is that you don’t need to have an account to use it with PHP.

The following function takes a long url as a parameter and return a shorter url, using the TinyUrl url shortener.

function getTinyUrl($url) {
    return file_get_contents("".$url);


Shorten urls using

In the previous snippet of that article, I’ve shown you how you can shorten your urls using This is cool, but I’m pretty sure some of you prefer using the service. No problem, you can still use PHP to get your shortened url.

function bitly($url) {
	$content = file_get_contents("".$url."&format=xml");
	$element = new SimpleXmlElement($content);
	$bitly = $element->data->url;
		return $bitly;
	} else {
		return '0';

To use the function, simply use the following:

echo bitly("");


  • Dan

    Great little list of snippets, thank you

    I’ll be trying a few of these shortly!!

  • Joe Fanai

    Love that Friendship testing snippet!

  • Here’s the first two snippets consolidated into 4 lines (not including the example code). Also, makes it easy to get to all of the data returned by ‘users/show.xml’

  • Tanmay

    Nice article.

  • Nice Roundup! 😉

  • some of hosts disable opening remote files…

  • Excellent! I’ve been looking for this information for a while now, and you deliver the goods. Thanks!

  • Very nice, definitely going to be using some of those. Thanks a lot!

  • Jon

    Amazing, super helpful. I was using a plugin for showing number of twitter followers – always love to be able to add things into the theme directly instead. Thanks again.

  • That’s an awesome list of snippets. Anytime you can do something without a plugin I’m all for it (retweeted).

  • Practically for all of these, you can use the JSON API format and save on preg stuff (which is heavy and ugly).

    On the example of the first snippet:

    function get_followers($twitter_id) {
    $get = file_get_contents(''.$twitter_id);
    $res = json_decode($get);

    return $res->followers_count;

  • Great post. I am going to implement some of these code snippets on my future projects. Thanks!

  • Awesome! thanks for these. bookmarked 🙂

  • Pingback: - WordPress News, Themes, Tutorials, Plugins, Questions, ...()

  • Beware of the example you’ve used for updating your status: when a user is not already logged in to Twitter, the given status will be discarded by Twitter.

    Instead, use the following (note: “/home”):
    “ Hi Jean, how are you?”

    That will redirect a user to the login screen, and forward them to a page where he will see the specified status, waiting to be tweeted.

    Subtile difference. 😉

  • Thanks for mentioning those snippets with us, will surely try to use these..

  • Use CURL instead of file_get_content. Opening remote files is often disabled due to security.

  • Thanks a lot … I was in search of this… was not getting from long day .. Superb information.. Hope this code will help others too..

    Thanks 🙂 Jung

  • Nice! I’m going to implement this on my sites. Thanks for sharing especially in your effort to include snippets just so we could follow the instructions.

  • kathy

    salut jean baptiste. i don’t think the tweetmeme counts links that were retweeted with the bitly link shortening snippet. any idea how to make the 2 play together?

  • kathy

    never mind. i think it is just not counting my multiple tweets of the same link.

  • Alex Vallejo

    Can someone describe in layman’s terms how cURL is used in conjunction with PHP to display your Tweets

    -noob php developer

  • Great snippet! I will implement this to my future sites. Really works wonders!


    // Caspar

  • I’m using the ‘Get latest Twitter status’ it works good but its only grabbing the first one is they anyway I can change the amount grabbed ? also links within the Twitter posts are showing up like ‘’ How would I go around amending this ?

  • plugin for showing number of twitter followers will be much more useful.

  • So glad I stumbled on this resource. I just got set up creating a new blog on WordPress using a WooTheme. Been looking for some ways to tweak the PHP to bring a bit more attention to my Twitter account.

    You’ve made things super easy and saved me time. For that, I am grateful!


  • Lucky to have stumbled on this post. We’re looking to redesign our page for the new year and this looks like it’s worth a try. Thanks a lot! Do you have posts discussing PHP interactions with other social media outlets?

  • Do you have the PHP codes with OAuth implementation for above tasks?