-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.

1

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Works like a charm. Thanks!
If this solved your problem, please click the checkmark on the left of the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.