sebi
sebi

Reputation: 837

How can I fix this error about stdClass in PHP

This is my code:

$array = array(
"Birds" => 
array(
'group' => 1,
"Bird" => array(

array('id' => 1, 'img' => "img1.png", 'title' => "kate"),
array('id' => 2, 'img2' => "img2.png", 'title' => "mary")
)) );


$json = json_encode($array);
echo json_decode($json);

OUTPUT IS:

//JSON OUTPUT {"Birds":{"group":1,"Bird":[{"id":1,"img":"img1.png","title":"cardinal"},{"id":2,"img2":"img2.png","title":"bluejay"}]}}

Object of class stdClass could not be converted to string

Upvotes: 0

Views: 382

Answers (3)

Night2
Night2

Reputation: 1153

You have to pass the second parameter of json_decode as true, more info about these parameters at: http://php.net/manual/en/function.json-decode.php

so your echo json_decode($json); should be changed to this:

print_r(json_decode($json, true));

echo is changed to print_r since the output is an array not a string ...

Upvotes: 0

Aurimas Ličkus
Aurimas Ličkus

Reputation: 10074

Use var_dump to view variables echo converts your variable to string, while it's object. Also you can add second param to json_decode($data, true) to get array instead object, as i assume that's what you want, because input is array.

About object convertion to string you can read __toString

Upvotes: 0

benedict_w
benedict_w

Reputation: 3598

try

var_dump($json);

This allows you to print out the details of objects and other non-primative types.

Echoing is used for strings - Your json decoded string will be an object of type stdClass

See var_dump http://php.net/manual/en/function.var-dump.php

See echo http://php.net/manual/en/function.echo.php

Upvotes: 1

Related Questions