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){ $xml=file_get_contents('http://twitter.com/users/show.xml?screen_name='.$twitter_id); if (preg_match('/followers_count>(.*)</',$xml,$match)!=0) { $tw['count'] = $match[1]; } return $tw['count']; }
$nb = get_followers('phpsnippets'); echo "PHP Snippets already have ".$nb." followers!";
Sources: http://www.phpsnippets.info/get-twitters-followers-in-php
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?
Twitter is extremely popular these days, and many clients already asked me to display their status on their website. Doing so is quite easy using cURL. This snippet will return the status of any Twitter user.
function get_status($twitter_id, $hyperlinks = true) { $c = curl_init(); curl_setopt($c, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$twitter_id.xml?count=1"); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); $src = curl_exec($c); curl_close($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">