Print data from a JSON with PHP

2

I want to print data specific to a JSON.

I have the following code:

  <?php
    $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, 'https://lan.api.riotgames.com/api/lol/LAN/v1.4/summoner/by-name/'.$summoner.'?api_key='.$key);
    $result = curl_exec($ch);
    curl_close($ch);

    $obj = json_decode($result);

    print_r($obj);
    ?>

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
source

2 answers

1

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
source
0

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:

$obj['erickreplay']['id'];
    
answered by 03.06.2017 в 12:26