无法使用cURL返回的数据?

时间:2016-03-28 00:47:24

标签: php json curl

我使用cURL查询我的服务器,以便显示有关服务器的某些信息。

代码:

$url = URL . '/api.php';
$params= 'case=getinfo';

$ch = curl_init( $url );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$gameinfo = curl_exec($ch);

var_dump($gameinfo);

如果我转储返回的数据,我得到:

string(264) """{"hostname":"A Minecraft Server","gametype":"SMP","game_id":"MINECRAFT","version":"1.9","plugins":"CraftBukkit on Bukkit 1.9-R0.1-SNAPSHOT: PlayerData 1.0","map":"world","numplayers":"0","maxplayers":"200","hostport":"25565","hostip":"192.168.1.20","players":[]}"

我尝试过以下方式使用数据:

echo $gameinfo["hostname"];
echo $gameinfo->hostname;
echo $gameinfo[0]["hostname"];
echo $gameinfo[0]->hostname;
using foreach($gameinfo as $info)

对于每一个我要么得到非法字符串或非对象

那我怎么用?

1 个答案:

答案 0 :(得分:0)

看起来您的响应是JSON,在将其用作数组之前,您需要首先解码PHP。同时修剪报价

$gameinfo = curl_exec($ch);
$gameinfo = json_decode(trim($gameinfo, '"'), true);

var_dump($gameinfo);