Print data from a JSON with PHP


I want to print data specific to a JSON.

I have the following code:

    $summoner = "ErickReplay";
    $key = "mikey";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, ''.$summoner.'?api_key='.$key);
    $result = curl_exec($ch);

    $obj = json_decode($result);


It prints the following:

stdClass Object ( [erickreplay] => stdClass Object ( [id] => 143048 [name] => ErickReplay [profileIconId] => 547 [revisionDate] => 1496449271000 [summonerLevel] => 30 ) ) 

What I want is to print only the id which would be 143048. I have tried in different ways, but I can not get it.

asked by Erick Estevez 03.06.2017 в 11:08

2 answers


The correct way is to follow the hierarchical scheme of the object.

In the case that you show the response of the object.

stdClass Object ( [erickreplay] => stdClass Object ( [id] => 143048 //...
                   ^^^^^^^^^^^ key 1                  ^^ key 2

It would be like this, keeping each key as it appears in hierarchy order.

echo $obj->erickreplay->id;
           ^^^^^^^^^^^  ^^
           key 1        key 2

The error that you indicate, Undefined property: stdClass::$ErickReplay in... what it comes to say is that the key you are looking for $obj->ErickReplay is not defined.

answered by 03.06.2017 / 11:35

Another way to see this is to read the answer as an array and not as an object.

$obj = json_decode($result, true);

and the way to read the answer would be:

answered by 03.06.2017 в 12:26