Sourav Das
Sourav Das

Reputation: 727

How can I access specific data from nested json using php?

Here is JSON text-

{
  "kind": "youtube#commentThreadListResponse",
  "etag": "\"SJZWTG6xR0eGuCOh2bX6w3s4F94/CTTPi63Nf0uw0VTa1vFAqqL88k8\"",
  "pageInfo": {
  "totalResults": 2,
  "resultsPerPage": 20
  },

  "items": [
  {
    "kind": "youtube#commentThread",
    "etag": "\"SJZWTG6xR0eGuCOh2bX6w3s4F94/adPDtbu8m9cY9xkHacyKvWARfR8\"",
    "id": "Ugy2poa2UDXYm-kUKWh4AaABAg",
    "snippet": {
      "videoId": "kVUIh5cp3mY",
      "topLevelComment": {
        "kind": "youtube#comment",
        "etag": "\"SJZWTG6xR0eGuCOh2bX6w3s4F94/xgKA1zcXGWvsBnMxKuksawMPqy8\"",
        "id": "Ugy2poa2UDXYm-kUKWh4AaABAg",
        "snippet": {
          "authorDisplayName": "Thelma S. Brittain",
          "authorProfileImageUrl": "https://yt3.ggpht.com/a/",
          "authorChannelUrl": "http://www.youtube.com/channel/",
          "authorChannelId": {
            "value": "UC1W2wC96X4SjdAewhPi-mpg"
          },
          "videoId": "kVUIh5cp3mY",
          "textDisplay": "Hello thanks for the video.",
          "textOriginal": "Hello thanks for the video.",
          "canRate": true,
          "viewerRating": "none",
          "likeCount": 0,
          "publishedAt": "2019-06-28T17:48:18.000Z",
          "updatedAt": "2019-06-28T17:48:18.000Z"
        }
      },
      "canReply": true,
      "totalReplyCount": 0,
      "isPublic": true
    }
  }
 ]
}

I got this JSON text by using youtube API. I'm trying to echo 'authorDisplayName' and 'textOriginal' but it is not working. I tried in many ways. I can't figure out my mistake. I tried this far,

$url = file_get_contents("https://www.something.com");
$arr = json_decode($url, true);
echo $arr['items']->['snippet'][0]->['topLevelComment']->['snippet']->['authorDisplayName'];
echo $arr['items']->['snippet']->['topLevelComment']->['snippet']->['textOriginal'];

Can someone help me to fix this issue? Thanks.

Upvotes: 0

Views: 46

Answers (2)

Robin Gillitzer
Robin Gillitzer

Reputation: 1602

The second parameter true in $arr = json_decode($url, true); means, that you will get an associative array as return. You use object notation (->) and thats not working. Try with array notation like this:

echo $arr['items'][0]['snippet']['topLevelComment']['snippet']['authorDisplayName'];
echo $arr['items'][0]['snippet']['topLevelComment']['snippet']['textOriginal'];

Upvotes: 2

Nigel Ren
Nigel Ren

Reputation: 57121

You are mixing array and object notation in

echo $arr['items']->['snippet']->['topLevelComment']->['snippet']->['textOriginal'];

as you have converted the JSON to an associative array ( with true as the second parameter) and with the adjusted hierarchy...

$arr = json_decode($url, true);
echo $arr['items'][0]['snippet']['topLevelComment']['snippet']['authorDisplayName'];
echo $arr['items'][0]['snippet']['topLevelComment']['snippet']['textOriginal'];

Upvotes: 4

Related Questions