views:

59

answers:

2

Hi, I'm trying to display a number of Twitter followers using PHP given a username. My code looks like this:

function tweet_count() {

    $name = get_option('ws_twit');
    $twit = file_get_contents('http://twitter.com/users/show/'.$name.'.xml');
    $begin = '<followers_count>'; $end = '</followers_count>';
    $page = $twit;
    $parts = explode($begin,$page);
    $page = $parts[1];
    $parts = explode($end,$page);
    $tcount = $parts[0];
    if($tcount == '') { $tcount = '0'; }
    echo $tcount;
}

It usually works... except when it doesn't. Most of the time, it throws out an error:

failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in [filename] on line 8

Line 8 is: $twit = file_get_contents('http://twitter.com/users/show/'.$name.'.xml');

I tried hardcoding the username, but the effect is the same. I'm wondering if this code is okay, since it DOES sometimes work. First I assumed that maybe it was Twitter error but it happens way to often to be the case.

Thanks for your help!

+2  A: 

Most likely because of twitters ability to be down so much!

But you may also want to try out the following.

$name = get_option('ws_twit');
$twit = file_get_contents('http://twitter.com/users/show/'.$name.'.xml');
preg_match_all("|<followers_count>(.*)</followers_count>|U",$twit,$followers);
$tcount = $followers[1];
echo (!empty($tcount)) ? $tcount : 0;

UPDATE I just tried refreshing the url in browser a few times.. http://twitter.com/users/show/TWITTERNAME.xml and some worked but I did get the Bad Request error, it is deff twitter.

Lizard
Same effect, "HTTP request failed! HTTP/1.1 400 Bad Request" in the second line.
Justine
A: 

I agree with Lizard in that Twitter is down a lot, and this may cause your inconsistent behavior. I've used a similar call structure as yours to communicate with Twitter, but instead of /users/show/name.xml, I used this URL: http://twitter.com/statuses/user_timeline.xml?user_id=####### I'm not sure if this will help, but it's worth a try. Maybe this will be more reliable, even though it goes sometime down as well.

(Also, Twitter has been especially bad today: http://dl.dropbox.com/u/2320369/twitter_problems.png)

octopi
I was thinking that Twitter being down a lot, is causing the problem but it happens way too often for my liking. That's why I'm trying to find a bulletproof solution ;)
Justine
Also, my `/users/show/name.xml` works fine this particular moment, but `/statuses/user_timeline.xml` throws back "Bad request, unauthorized in line blahblah".
Justine