Quantcast
Channel: Ross Tanner » social media
Viewing all articles
Browse latest Browse all 2

PHP Tutorial – Get your Twitter statuses

$
0
0

Twitter has fast become one of the most powerful social media platforms along with it’s great rival Facebook and the newcomer to the scene – Google+. Twitter is easily the best platform for companies and people “looking to be found” due to it’s potential reach. The hash tags, trends and search functionality makes it possible for one person in England to see the tweets of someone in Venezuela (most random country I could think of!). This wouldn’t be possible with Facebook due to it’s networking “restrictions” and also you may have to be friends with that person first. Facebook also exposes A LOT more personal information making Twitter by far the better platform for promoting blog posts, discussing trends and communicating with other people in your niche market.

Having a section on your website with your tweets or even tweets from every employee in your company is becoming a very popular choice amongst web builders and agencies. It aids with the promotion of your Twitter accounts and opens an extra contact avenue for potential clients. It is much easier to build than many people think too – a simple call to the Twitter API and you can even bypass database interaction if this is something that would make you have doubts.

I strongly suggest using a database though and run a “tweet loader” in the background – perhaps on a scheduled task – then display the tweets on the page to the user directly from the database. From this you could even cache the results to prevent heavy load on your own and Twitter’s servers. This not only increases load time of your web pages but you could take things a step further and implement a bad word / swear word filter and alter the accounts displayed on-the-fly.

The first step is to decide which Twitter accounts that you want to get the tweets for. I suggest starting with just one account and expaning how and when you wish at a later date. For the sake of this tutorial I will use just one account although adapting this for multiple accounts should be pretty obvious to you once we are done here. A simple line of code to start the procedure can be seen below where I just define the username that I want to query for. Always leave out the “@” symbol at the front of the username.

<?php

    // define the account username
    $account = "rossytzoltan";

?>

The next step would be to set up the Twitter API integration. We will query Twitter’s REST API for statuses for this username by sending the request to a specified URL with the parameters attached. The Twitter API can be accessed at the following location:

http://api.twitter.com/

To start the integration we will define the path to the REST API and then the request that we wish to send. I have split this into two variables although you are within your rights to merge this into one. For simplicity I have split them into $path and $request as they essentially indicate two seperate things.

<?php

// define the path to the feed of tweets
$path = "http://api.twitter.com/1/statuses/user_timeline.xml";

// set the request for the API
$request = "?include_rts=true&screen_name=".$account."&count=5";

?>

There are many more options that can be used in the $request but I have just used the ones needed which are:

  • include_rts – boolean – whether or not to display retweets in the status list.
  • screen_name – string – the Twitter account.
  • count – integer – the amount of tweets to grab.

Now that we have defined our path and request we can merge these together into one URL and query the API. As the response from the API will be in XML (eXtensible Markup Language) we will use SimpleXML to format this response into an object ready to use. Here is how this is achieved:

<?php

// get the response from the API as an object
$tweet_list = simplexml_load_file($path.$request);

?>

If you were to print_r() the $tweet_list variable then you will see exactly what is contained in the data. At the time of writing this article (11th January 2012) there are only three nodes in each tweet that we are going to need in order to set this up which are the actual tweet text, the time and date of which the tweet was submitted and the profile image for the user who tweeted. By using just these three items we can display our latest tweets on our website without cluttering it up. In order to get these three items though we need to loop through the tweets contained in the object then pull them out ready for use.

<?php

// check for Twitter posts
if ( count ( $tweet_list ) > 0 ) {

    // define the array of tweets
    $tweets = array();

    // loop through each Twitter post
    foreach ( $tweet_list as $tweet ) {

        // add the tweet to the array of tweets
        $tweets[] = array (
            'tweet'    =>    (string) $tweet->text,
            'posted'   =>    (string) $tweet->created_at,
            'image'    =>    (string) $tweet->user->profile_image_url
        );

    }

    // output how many tweets were loaded
    echo count($tweets)." were found.";

} else {

    // output a message to show no tweets found
    echo "No tweets were found.";

}

?>

That’s it you have successfully queried the Twitter API, retrieved the tweets and stored them into the $tweets array ready to be used. If you wanted to take it a step further and display them then here is the full code with @username and link replacing plus a bit of styling thrown in for good measure.

<?php

	// define the account username  
    $account = "rossytzoltan";  
	
	// define the path to the feed of tweets  
	$path = "http://api.twitter.com/1/statuses/user_timeline.xml";  
	  
	// set the request for the API  
	$request = "?include_rts=true&screen_name=".$account."&count=5";  
	
	// get the response from the API as an object  
	$tweet_list = simplexml_load_file($path.$request);  
	
	// check for Twitter posts  
	if ( count ( $tweet_list ) > 0 ) {  
	  
		// define the array of tweets  
		$tweets = array();  
	  
		// loop through each Twitter post  
		foreach ( $tweet_list as $tweet ) {  
		
			// format links to a clickable link
			$tweet->text = preg_replace("/http:\/\/([^ ]+)/i", "<a href=\"http://$1\">http://$1</a>", $tweet->text);
		
			// format @USERNAME into a link
			$tweet->text = preg_replace("/@([^ ]+)/", "<a href=\"http://twitter.com/$1\" target=\"_blank\">@$1</a>", $tweet->text);
	  
			// add the tweet to the array of tweets  
			$tweets[] = array (  
				'tweet'    =>    (string) $tweet->text,  
				'posted'   =>    (string) $tweet->created_at,  
				'image'    =>    (string) $tweet->user->profile_image_url  
			);  
	  
		}  
	  
		// output how many tweets were loaded  
		$amount_tweets = count($tweets);  
	  
	} else {  
	  
		// output a message to show no tweets found  
		$amount_tweets = 0;
	  
	}  

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Load Tweets</title>
    <style>
		ul li{list-style:none;clear:both;overflow:auto;margin-bottom:10px;}
		ul li span.img{float:left;width:48px;height:48px;background:green;}
		ul li span.tweet{float:left;margin:5px 0 0 10px;}
		ul li span.tweet span{color:#999;}
	</style>
</head>

<body>
	<p><strong><?php echo $amount_tweets; ?> tweets from <a href="http://twitter.com/<?php echo $account; ?>" target="_blank">@<?php echo $account; ?></a></strong></p>
    <ul>
<?php 

	// loop through each available tweet
	foreach ( $tweets as $tweet ) { 
		
?>
    	<li>
        	<span class="img"><img src="<?php echo $tweet['image']; ?>" /></span>
            <span class="tweet"><?php echo $tweet['tweet']; ?><br /><span><?php echo $tweet['posted']; ?></span></span>
        </li>
        <?php } ?>
    </ul>
</body>
</html>

If you liked this tutorial and found is useful please do tweet about it or follow me @rossytzoltan for more of the same. There is also a comments section below in case you have any praise or comments that you would like to add.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images