BGG
BGG

Reputation: 23

PHP json_decode returns array and NOT an object

I have to do a website with PHP and actually I'm trying with it. For now I want to obtain a JSON from a URL (I've got a web service with Node.js) and show in the screen. The URL returns a JSON object like this:

[{"name":"Juan","text":"Oh my god"},{"name":"Pedro","text":"I'm here"}]

I have this code in PHP file:

<?php 
    $data = file_get_contents('http://localhost:3000/node/busca'); // Returns the JSON
    $terminos = json_decode($data);

    print_r($terminos);

    echo $terminos->name;

?>

But print_r returns:

Array ( 
     [0] => stdClass Object ( 
            [name] => Juan 
            [text] => Oh my god
         ) 
     [1] =>  stdClass Object ( 
            [name] => Pedro
            [text] => I'm here
         )
 )

The echo says

Notice: Trying to get property of non-object in C:...\index.php on line 17

What can I do? json_decode should return an object and not an array.

Upvotes: 0

Views: 2735

Answers (4)

AbraCadaver
AbraCadaver

Reputation: 78994

The JSON and the decoded PHP is an array of objects. Try:

echo $terminos[0]->name;

You have multiple array elements so:

foreach($terminos as $object) {
    echo $object->name;
}

Upvotes: 4

C W&#252;rtz
C W&#252;rtz

Reputation: 864

See json_decode

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )


$terminosFalse = json_decode($data, true);
array(2) {
  [0]=>
  array(1) {
    ["attribute"]=>
    string(1) "attr1"
  }
  [1]=>
  array(1) {
    ["attribute"]=>
    string(1) "ATTR2"
  }
}


$terminosTrue = json_decode($data, false);
array(2) {
  [0]=>
  object(stdClass)#1 (1) {
    ["attribute"]=>
        string(1) "attr1"
  }
  [1]=>
  object(stdClass)#2 (1) {
    ["attribute"]=>
    string(1) "ATTR2"
  }
}

Upvotes: 0

Ryan
Ryan

Reputation: 28187

Edited to OP's question to re-format the array output to:

Array ( 
     [0] => stdClass Object ( 
            [name] => Juan 
            [text] => Oh my god
         ) 
     [1] =>  stdClass Object ( 
            [name] => Pedro
            [text] => I'm here
         )
 )

Looking at it like this it is quite clear how the individual objects are wrapped and addressable:

foreach ($terminos as $idx => $obj ) {
    echo "Name $idx: " $obj->name . PHP_EOL;
    /// ... etc
}

Should output:

Name 0: Juan 
Name 1: Pedro 

Upvotes: 1

Joshua Behrens
Joshua Behrens

Reputation: 818

Your data is an encoded array of objects. So you will get an array of objects. Everything is right here.

Upvotes: 1

Related Questions