HJGBAUM
HJGBAUM

Reputation: 397

Why doesn't json_decode work with this particular json object?

So I have my php script to receive a json object from http://www.reddit.com/search.json via a http GET request and through previous testing, DOES successfully get a json object. However, when I use json_decode on this object, I get an error:

Catchable fatal error: Object of class stdClass could not be converted to string in /home/hudson/ug/xbvg52/public_html/stupid.php on line 5

Here is my (very simple) code:

$query = $_GET["radio"];
$url = "https://www.reddit.com/search.json?q=".$query;
$response = file_get_contents($url);
echo json_decode($response);

How can I convert this JSON object into a string?

Upvotes: 0

Views: 80

Answers (2)

stevenwasserman
stevenwasserman

Reputation: 11

I believe the error you are seeing is because you are echoing an object. Echo is only used for strings. Use print_r or var_dump instead.

Upvotes: 1

Phiter
Phiter

Reputation: 14982

You can't echo json_decode because this function makes an array of objects, or a simple object. Try running var_dump(json_decode($response)); and see for yourself.

You're getting this error because echo expects a string and you're sending an object.

You could transform this array into a string in order to echo it.

Upvotes: 3

Related Questions