如何只获取一个json对象的值

时间:2014-11-23 11:45:12

标签: php json

我有my API的以下输出:

{
   "profiles":[
      {
         "id":"d2501196e8ed4d729b3727dc64989431",
         "name":"infiniman"
      }
   ],
   "size":1
}

但我只想显示id部分。

我可以用PHP做到吗?

代码:

<?php
header('Content-type: application/json');
ini_set("display_errors", false);
$user = $_GET['user'];
$arr = array("name"=>$user, "agent"=>"minecraft");
$data = json_encode($arr);

$ch = curl_init('https://api.mojang.com/profiles/page/1');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

if(!($res = curl_exec($ch))) {
echo('[cURL Failure] ' . curl_error($ch));
}

curl_close($ch);
echo $res;
$username = json_decode($res, true);
echo 'UUID: ' . $username->profiles[0]->id;
?>

1 个答案:

答案 0 :(得分:3)

查看json_decode()

$json = '{
   "profiles":[
      {
         "id":"d2501196e8ed4d729b3727dc64989431",
         "name":"infiniman"
      }
   ],
   "size":1
}';

$obj = json_decode($json);

echo $obj->profiles[0]->id;