0

Im decoding a json string, with this code:

$response = (string) file_get_contents($api);
$response = json_decode($response);
echo $response->MySomeKey;

I got this error: Object of class stdClass could not be converted to string.

Why i got this error, and how i can fix it simply?

Monroe41
  • 21
  • 2
  • `MySomeKey` is also an object of type `stdClass `. Try a `var_dump` instead a `echo`, you will see what it looks. – Ugo T. May 16 '19 at 15:46
  • i'm still pretty new to this, but i usually get that error when i try and echo out an array. what do you get if you `print_r($response);` instead of echo? – Sam.92 May 16 '19 at 15:46
  • With var_dump, not work's, echo $response->var_dump(result), i put wrong var_dump? – Monroe41 May 16 '19 at 15:49
  • Sam.92, it means im calling a not existent key inside the json $response? – Monroe41 May 16 '19 at 15:52
  • Ugo T., I need your help :( – Monroe41 May 16 '19 at 16:03
  • Sam.92 HELP ME PLS!! – Monroe41 May 16 '19 at 16:09
  • We can't really help further without you doing a `print_r($response)` as Sam said and editing you post to add that content in. – Chris White May 16 '19 at 16:50
  • 1
    Possible duplicate of [Object of class stdClass could not be converted to string](https://stackoverflow.com/questions/3607550/object-of-class-stdclass-could-not-be-converted-to-string) – miken32 May 16 '19 at 16:54
  • Thank you Chris White, but all is right!, and the solution found... – Monroe41 May 16 '19 at 20:58
  • And miken32, thanks by add that post... – Monroe41 May 16 '19 at 20:58
  • N.B. you're correct, `echo $response->var_dump(result)` is completely wrong. The $response object doesn't have a method called var_dump. var_dump is a built-in function in PHP used for debugging, to write out the whole contents of a variable. See https://www.php.net/manual/en/function.var-dump.php . In your case `var_dump($response);` would be what you would have needed. – ADyson May 16 '19 at 22:20

1 Answers1

1

Finally i found the solution, my problem was i try to print using echo of a key(MySomeKey) json(object), i have to print using echo the value of the key not the key(object):

$response = (string) file_get_contents($api);
$response = json_decode($response);
echo $response->MySomeKey->MyKeyValue;

result:

"MyValueOfSomeKey"

Thanks to Ugo T. and Sam.92, I found the bug and i build this solution.

Monroe41
  • 21
  • 2