phpjson

Use Variable in object echo


$data = file_get_contents("API LINK HERE");
$json = json_decode($data);

echo($json->zhohar->name);

What I want to do is replace zhohar in the echo with a variable which is defined by user input. So in the end I have something like this

$username = $_POST['username'];

$data = file_get_contents("API LINK HERE");
$json = json_decode($data);

echo($json->$username->name);

But this obviously doesn't work. Anyone has an idea how to solve this?


Solution

  • You can do something like this:

    echo $json->{$username}->name
    

    Or:

    $json = json_decode( $data, true );
    echo $json[$username]['name'];