简体   繁体   中英

Trouble with output in PHP with JSON object (possibly array?)

I'm having troubles getting a JSON object (possibly an array?) to output using PHP. My question is: How do I get only a displayName from the following (shortened) JSON object using PHP?

{"Response":
  {"results":
    [{"user":
      {"membershipId":"6343960","displayName":"J Raider"},"hasPendingApplication":false},
     {"user":
      {"membershipId":"4479502","displayName":"T Ellis"},"hasPendingApplication":false}]
  }
}

What I've tried so far:

var_dump($json); 
echo $json; 
echo $json->Response->results->user->displayName;
echo $json->Response->results[0]->user->displayName; 
echo $json->Response->results[0]->user[0]->displayName; 
echo json_encode($json, JSON_PRETTY_PRINT);
print_r($json)

My results have either been "null" "NULL" or simply no output. I am pulling from the Bungie API using the following code:

<?php 
    $apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.bungie.net/Platform/Group/1179713/Members/?lc=en&fmt=true&currentPage=1&platformType=1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-API-Key: ' . $apiKey));

$json = json_decode(curl_exec($ch)); // edited to correct curl_init to  curl_exec

var_dump($json);

?>

I am aiming to do this as a web service using PHP. The Bungie API documentation says a JavaScript GET request will not work, so I'd like to stick with PHP for the request and the output.

To clarify my question: how do I use PHP to output the displayName from this JSON object?

Thanks in advance for your help and please let me know if I need to clarify anything.

just use the json_decode() function then iterate through the array in results like so

$decoded = json_decode($json);//this will give anarray from your json 
$obj = $decoded->Response->results;
foreach ($obj as $ar) {
  $displayName = $ar->user->displayName;
  echo $displayName . "<br>";
}

let me know if you need more help

Im pretty sure this is failing because you arent executing your curl post:

$json = json_decode(curl_init($ch));

should be

$json = curl_exec($ch);
$json = json_decode($json,true);
var_dump($json); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM