-1

How would I go about parsing JSON from YouTube into PHP variables? Here is the JSON that I receive from the YouTube API.

{
 "kind": "youtube#videoListResponse",
 "etag": "\"dc9DtKVuP_z_ZIF9BZmHcN8kvWQ/Mlc20HEmv6-VVTw4GdCc1f-zXBc\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#video",
   "etag": "\"dc9DtKVuP_z_ZIF9BZmHcN8kvWQ/ynrMYdueGEZMM0sWKi_kmMBjv4o\"",
   "id": "e-ORhEE9VVg",
   "contentDetails": {
    "duration": "PT4M33S",
    "dimension": "2d",
    "definition": "hd",
    "caption": "false",
    "licensedContent": true
   },
   "statistics": {
    "viewCount": "1092004149",
    "likeCount": "4304240",
    "dislikeCount": "314746",
    "favoriteCount": "0",
    "commentCount": "412998"
   }
  }
 ]

How would I parse it into variables? For example I would like to extract the view count into $viewCount.

Anonymous
  • 11,740
  • 3
  • 40
  • 50
Keith
  • 49
  • 1
  • 8

1 Answers1

4

You can use json_decode() to parse the data:

$data = json_decode($input, true);

foreach($data["items"] as $item) {
    echo $item["statistics"]["viewCount"];
}

Note that the ‘items‘ property is an array, so you could have 0, 1 or more results. That is why iteration is necessary (you could do $viewCount = $data['items'][0]['statistics']['viewCount']; if you're sure there is one result, I wouldn't recommend it though).

Anonymous
  • 11,740
  • 3
  • 40
  • 50