Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Json_decode to array

I am trying to decode a JSON string into an array but i get the following error.

Fatal error: Cannot use object of type stdClass as array in C:\wamp\www\temp\asklaila.php on line 6

Here is the code:

<?php
$json_string = 'domain.com/jsondata.json';

$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata);
print_r($obj['Result']);
?>
by

3 Answers

akshay1995
try this

$json_string = 'domain.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
echo "<pre>";
print_r($obj);
kshitijrana14
This will also change it into an array:
<?php
print_r((array) json_decode($object));
?>
pankajshivnani123
This is a late contribution, but there is a valid case for casting json_decode with (array).
Consider the following:

$jsondata = '';
$arr = json_decode($jsondata, true);
foreach ($arr as $k=>$v){
echo $v; // etc.
}

If $jsondata is ever returned as an empty string (as in my experience it often is), json_decode will return NULL, resulting in the error Warning: Invalid argument supplied for foreach() on line 3. You could add a line of if/then code or a ternary operator, but IMO it's cleaner to simply change line 2 to ...

$arr = (array) json_decode($jsondata,true);
... unless you are json_decodeing millions of large arrays at once, in which case as @TCB13 points out, performance could be negatively effected.

Login / Signup to Answer the Question.