开发者

Trying to show my Twitter followers count on my website with no luck

This is the code I am using, but it does return blank in m开发者_C百科ost cases.

<?php
$xml=file_get_contents('http://twitter.com/users/show.xml?screen_name=MyTwitterUsernameBla');
if (preg_match('/followers_count>(.*)</',$xml,$match)!=0) {
$count = $match[1];
}
echo $count;
?>

I want to show Twitter followers count in simple way, no plugins..it's a website, and not a blog.

Thank you very much :)


If it works on your localhost but not on your public host, then chances are that Twitter is either blocking or throttling your public server's IP. Many shared hosts get blocked/throttled because there are multiple sites banging away at the Twitter API without authentication. Twitter views them as one app and throttles the IP as a whole.

To get around this, you're going to need to authenticate using oAuth. It's a pain in the ass, but it's a necessary step. Here are some resources that you might find to be handy:

  • http://blog.evandavey.com/2010/02/how-to-php-oauth-twitter.html
  • http://pear.php.net/package/HTTP_OAuth/redirected

Twitter offers you some credentials in the "Your Apps" section of the Twitter Developer website. Once you've registered your site as an app, click on My Access Token. That will give you a key/token that you can use to successfully authenticate.


Another thought is that Twitter is simply throttling your app. If this is the case, it's because you've got too much traffic and you're not caching the API results. Cache the results of the API for, say, an hour before fetching a new copy. Twitter will stop singling you out if you do this.

if(filemtime("cache.xml") < (int)$_SERVER["REQUEST_TIME"] - 3600) {
    $data = file_get_contents("http://twitter.com/users/show.xml?screen_name=username");
    file_put_contents("cache.xml", $data);
} else
    $data = file_get_contents("cache.xml");


Think your reg. exp. is too greedy.. believe it will match everything up until the last '< /'

try something like a non-greedy match:

/followers_count>(.*?)</

or match everything except '<' :

/followers_count>([^<]*)</

Parsing the XML might be easier, and if you want to extract a lot from the xml, more "correct". But seems like overkill in your case.


It's much better (more reliable and easier to maintain) to use an XML parser than to try to fetch bits with regular expressions.

Simply:

$xml = new SimpleXMLElement('http://twitter.com/users/show.xml?screen_name=username', null, true);

echo $xml->followers_count;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜