如何使用php和cURL显示JSON对象?

时间:2013-11-08 15:50:29

标签: php json curl

我是php的新手(事实上我几乎一无所知)而且我试图在网站上显示JSON字符串中的对象(可能不是正确的术语,但你知道......我新的...)。这是我正在使用的cURL代码:

$url="http://mc.gl:8081/?JSONSERVER=lobby";
//  Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);

然后我有这个应该做某事(我真的不明白)

// Will dump a beauty json :3
var_dump(json_decode($result));

Annnnnddd ......接下来我该怎么办?我做了很多谷歌搜索,似乎没有任何工作。这是我应该得到的字符串:

{"lobby":{"playeramount":1,"players":{"MisterErwin":"MisterErwin"}},"API-Version":"1","return":true}

我希望回应“ playeramount ”。

任何帮助将不胜感激!非常感谢!

2 个答案:

答案 0 :(得分:2)

PHP中的var_dump()函数用于显示有关变量的结构化信息。它通常用于调试,与JSON解码无关。

在这种情况下,$result变量将包含您需要的JSON字符串。要解码它,请使用PHP的内置函数json_decode()

$json = json_decode($result); // decode JSON string into an object

注意:通过将TRUE作为第二个参数传递给json_decode(),也可以获得关联数组。

获得对象后,可以遍历它以获得所需的值:

echo $json->lobby->playeramount;

Demo!

答案 1 :(得分:1)

如果您想以 associative array 的形式访问结果,您也可以这样做[通过在{{1}中传递 true 标记功能]

json_decode()