使用PHP从JSON字符串中提取项目

时间:2015-06-23 20:50:17

标签: php json

假设我有这个JSON字符串:

{
 "kind": "youtube#searchListResponse",
 "etag": "\"Y3xTLFF3RLtHXX85JBgzzgp2Enw/aEjB0uWRf7BN9_0Kkzd0ZK9uqkw\"",
 "nextPageToken": "CAEQAA",
 "pageInfo": {
  "totalResults": 76061,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"Y3xTLFF3RLtHXX85JBgzzgp2Enw/T9Y8RT9FLOEgb7ql2XZUv7PpAGU\"",
   "id": {
    "kind": "youtube#channel",
    "channelId": "UCcB3bcWy0_QK7uPQvTD0LwQ"
   }
  }
 ]
}

如何从中提取channelId作为新变量?

2 个答案:

答案 0 :(得分:4)

您可以使用json_decode

$json = /* your json string */;
$obj = json_decode($json);
$channel = $json->items[0]->id->channelId;

答案 1 :(得分:1)

首先,您需要使用json_decode()解码json数据,然后才能获得值。如下所示: -

$json = $json_string;// suppose your json string variable name is $json_string
$std_obj_data = json_decode($json); // now you will get STD class Object
$channel = $std_obj_data->items[0]->id->channelId; // fetch channelId;

例如: - https://eval.in/386415