开发者

Decoding JSON feed via PHP from Twitter not working?

So I'm pulling down a user's tweet steam in JSON format via PHP. I'd like to decode it into an associative array or at least some more usable fashion rather than a string so that I can m开发者_如何学JAVAaneuver through it.

I've been reading like mad about json_decode, but for me it seems like when I use it, before and after, the contents of the file is still being detected as one long string. Can anyone help me figure out what I am doing wrong?

$url = "http://twitter.com/status/user_timeline/" . $username . ".json?count=" . $count . "&callback=?";    

// $url becomes "http://twitter.com/status/user_timeline/steph_Rose.json?count=5&callback=?";   
        $contents = file_get_contents($url);
        $results = json_decode($contents, true);

        echo "<pre>";
        print_r($results);
        echo "</pre>";

        echo gettype($results); // this returns string


With callback in the URL, you get a string back that is wrapped in parenthesis ( ) (excerpt of the string):

([{"in_reply_to_user_id":  /* ...more data here...*/ }]);

This is not valid JSON.

Without callback, the result is only wrapped in [ ] which is valid:

 [{"in_reply_to_user_id":  /* ...more data here...*/ }]


Ditch the &callback=? in the url.


I was used to parsing JSON using the jQuery library, so I had the &callback=? at the end of the URL.

It seems as if I take this off, that json_decode() has no problem converting the data, then, to an array.

If anyone knows the reason why this would be, I would love to know.

Long story short, it works!!


   $url = "http://twitter.com/status/user_timeline/" . $username . ".json?count=" . $count;

remove the callback so your json is json and not jsonp, jsonp breaks on decoding

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜