...

View Full Version : Need help getting Json_decode obj PHP5



Bobafart
11-02-2009, 01:52 AM
Hello, I created a function which posts a link to a URL shortening API and returns the results in JSON format. Having trouble outputting the results.


My func:


function get_bitly_shorturl($longurl) {
$url = "http://api.bit.ly/shorten?version=2.0.1&login=myusernamer&apiKey=myapikey&format=json&history=1" . "&longUrl=".urlencode($longurl);

// in the above link i have removed my username and my api key for posting on this forum

//using curl
$curlObject = curl_init();
curl_setopt($curlObject,CURLOPT_URL,$url);
curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curlObject,CURLOPT_HEADER,false);

$result_json = curl_exec($curlObject);
curl_close($curlObject);

// decode JSON. Assumes that it is PHP5
var_dump(json_decode($result_json));
$resultJson = json_decode($result_json);

echo $resultJson['results'][$longurl]['shortUrl'];
return $resultJson['results'][$longurl]['shortUrl']; // this line gives me the following error: Fatal error: Cannot use object of type stdClass as array in /home/myscript/path/myscript.php on line 24
}


the var_dump is:



object(stdClass)#1 (4) { ["errorCode"]=> int(0) ["errorMessage"]=> string(0) "" ["results"]=> object(stdClass)#2 (1) { ["http://www.mylongurl.com"]=> object(stdClass)#3 (4) { ["hash"]=> string(5) "blajadsdf324" ["shortKeywordUrl"]=> string(0) "" ["shortUrl"]=> string(20) "http://bit.ly/dsd4wscY" ["userHash"]=> string(6) "dsd4wscY" } } ["statusCode"]=> string(2) "OK" }


I am unable to echo or return the shortUrl in my $resultJson object. Can someone help?

return $resultJson['results'][$longurl]['shortUrl']; appears to give the fatal error

I have tried a number of different methods, including: return $resultJson['results']['shortUrl'];

same error

please help

Bobafart
11-02-2009, 02:00 PM
can anyone tell me why this doesn't work?

please?

barkermn01
11-02-2009, 02:21 PM
can anyone tell me why this doesn't work?

please?



object(stdClass)#1 (4) {
["errorCode"]=> int(0)
["errorMessage"]=> string(0) ""
["results"]=> object(stdClass)#2 (1) {
["http://www.mylongurl.com"]=> object(stdClass)#3 (4) {
["hash"]=> string(5) "blajadsdf324"
["shortKeywordUrl"]=> string(0) ""
["shortUrl"]=> string(20) "http://bit.ly/dsd4wscY"
["userHash"]=> string(6) "dsd4wscY"
}
}
["statusCode"]=> string(2) "OK"
}

Use <pre> tags around a var_dump presents its easier and make easier for others to help you
So to get your Val you want to do


$var = json_decode();
$add = $var->results->http://www.mylongurl.com->shortUrl;

But that wont work due to the // so sorry i cant be much help but that's how JSON normally works



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum