Amy Neville
Amy Neville

Reputation: 10621

Extract item from JSON string using PHP

Lets say I have this JSON string:

{
 "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"
   }
  }
 ]
}

How would I extract the channelId from that as a new variable?

Upvotes: 1

Views: 70

Answers (2)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

First of all you need to decode json data using json_decode()and then you can get values. So do like below:-

$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;

For example:- https://eval.in/386415

Upvotes: 1

dave
dave

Reputation: 64725

You would use json_decode:

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

Upvotes: 4

Related Questions