views:

337

answers:

4

Hello my fellow coders!

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 maneuver 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
+1  A: 

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!!

Stephanie
See my answer for the reason...
Felix Kling
+3  A: 

Ditch the &callback=? in the url.

chris
Yep that's exactly what I ended up doing. I understand callbacks, but why would that mess this up?
Stephanie
Because the returned string had parenthesis around it. That's just simply, invalid json. There's no need/purpose for them in json, so they aren't included in the definition. Keep in mind, json is not exactly the same as javascript.
chris
+2  A: 
   $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

antpaw
+6  A: 

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...*/ }]
Felix Kling
So I guess a callback is required for javascript due to it being client side and needing a trigger, but in PHP file_get_contents() will execute and the next step will not until the data has been read and stored. Just trying to figure out when to use the callback and when not to.As soon as I took it off, it worked. Thanks :) Checked as correct and voted up.
Stephanie