PHP中JSON对象(可能是数组?)的输出有问题
我在使用PHP输出JSON对象(可能是数组?)时遇到问题。我的问题是:如何使用PHP从以下(缩短的)JSON对象中仅获取显示名PHP中JSON对象(可能是数组?)的输出有问题,php,json,Php,Json,我在使用PHP输出JSON对象(可能是数组?)时遇到问题。我的问题是:如何使用PHP从以下(缩短的)JSON对象中仅获取显示名 {"Response": {"results": [{"user": {"membershipId":"6343960","displayName":"J Raider"},"hasPendingApplication":false}, {"user": {"membershipId":"4479502","displayN
{"Response":
{"results":
[{"user":
{"membershipId":"6343960","displayName":"J Raider"},"hasPendingApplication":false},
{"user":
{"membershipId":"4479502","displayName":"T Ellis"},"hasPendingApplication":false}]
}
}
到目前为止,我所尝试的:
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)
我的结果要么是“null”“null”,要么就是没有输出。
我使用以下代码从Bungie API中提取:
<?php
$apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.bungie.net/Platform/Group/1179713/Members/?lc=en&fmt=true¤tPage=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);
?>
我的目标是将其作为一个使用PHP的web服务来实现。Bungie API文档说JavaScript GET请求将不起作用,因此我想继续使用PHP来处理请求和输出
为了澄清我的问题:如何使用PHP从这个JSON对象输出displayName
提前感谢您的帮助,如果我需要澄清任何事情,请告诉我。只需使用
json\u decode()
函数,然后在数组中迭代如下结果
$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>";
}
$decoded=json\u decode($json)//这将为您的json提供一个数组
$obj=$decoded->Response->results;
foreach($obj作为$ar){
$displayName=$ar->user->displayName;
echo$displayName。“
”;
}
如果您需要更多帮助,请告诉我我很确定这是失败的,因为您没有执行curl post:
$json=json_decode(curl_init($ch))代码>
应该是
$json = curl_exec($ch);
$json = json_decode($json,true);
var_dump($json);
var_dump(json_decode($json,true))
var_dump(json_decode($json,true))返回“NULL”:(你的curl_exec
?@Kisaragi非常注意细节!我用curl_init代替了curl_exec(哦!)。这也让我查看了其他详细信息以验证其他内容,我发现罪魁祸首是URL。它应该以“…”开头我错过了3个w。当我用简单的REST客户端Chrome扩展检查我的URL时,它正在默默地修复我的URL。感谢你帮助我找到这个错误,并询问了有关curl_exec的问题。:)你的代码看起来应该可以工作,但在我的情况下它不会产生输出。你确定$json不是空的吗,尝试使用print_rUsing print_r($jason)打印它不会产生任何输出,但是,我通过Chrome扩展名“Simple REST Client”点击了具有相同标题的相同URL,并可以验证是否有返回的JSON对象。我在API的另一个端点使用了相同的cURL-GET-request方法,并收到了一个JSON对象,我可以使用print\r打印它。另一个JSON对象的区别在于没有[]括号。据我所知,我使用了正确的URL和正确的请求方法,但是当我尝试输出时出现了一些问题。你能重新发布第二个json吗?非常注意细节!我用curl\u init而不是curl\u exec(哦!)。这也让我查看了其他细节,以验证其他所有内容,我发现罪魁祸首就是URL。它应该以“…”开始,我错过了3W。当我用简单的REST客户端Chrome扩展检查我的URL时,它正在默默地修复我的URL。感谢您帮助我找到有关curl_exec的问题中的此错误。:)