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


How to display a JSON object with php and 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));

安南德....接下来我该怎么做?我做了很多谷歌搜索,似乎没有任何效果。这是我应该得到的字符串:

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

我想呼应"玩家数量"。

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

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;

演示!

如果你想以associative array访问结果,你也可以这样做[通过在json_decode()函数中传递一个真正的标志]

<?php
$str='{"lobby":{"playeramount":1,"players":{"MisterErwin":"MisterErwin"}},"API-Version":"1","return":true}';
$str=json_decode($str,true); // Setting the true flag 
echo $str['lobby']['playeramount']; //Outputs 1