dongxian6715 2015-12-15 21:46
浏览 80
已采纳

PHP中带有JSON对象的输出问题(可能是数组?)

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.

  • 写回答

2条回答 默认 最新

  • dongyi6845 2015-12-15 22:38
    关注

    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); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改