Conor Reid
Conor Reid

Reputation: 95

JSON Extracting Data Into Variable Using PHP

I'm using a YouTube data API request to grab the channel id, but i'm not too sure why it isn't working:

The returned JSON request i'm getting is:

{
     "kind": "youtube#channelListResponse",
     "etag": "\"PSjn-HSKiX6orvNhGZvglLI2lvk/k5qSWj-xcF96jAN3p1uQH1amSRc\"",
     "pageInfo": {
      "totalResults": 1,
      "resultsPerPage": 5
     },
     "items": [
      {
       "kind": "youtube#channel",
       "etag": "\"PSjn-HSKiX6orvNhGZvglLI2lvk/e1xTbLf6JLhwwzeWbdMfWdPfcwg\"",
       "id": "UC-lHJZR3Gqxm24_Vd_AJ5Yw"
      }
     ]
    }

To extract the JSON data i'm using the a few lines of code and a function in php:

$banner_data = file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=brandingSettings&forUsername=pewdiepie&key=AIzaSyDTxvTLWXStUrhzgCDptVUG4dGBCpyL9MY');
$banner_data = json_decode($banner_data, true);
$YTid = $banner_data['items']['id'];

When i :

echo "YouTube Channel Id Of pewdiepie is " . $YTid . ".<br />";

I don't get the channel id? What's my problem?

Upvotes: 0

Views: 359

Answers (2)

johnh10
johnh10

Reputation: 4185

Try this instead:

    $YTid = $banner_data['items'][0]['id'];

Upvotes: 1

vrijdenker
vrijdenker

Reputation: 1431

Items is an array containing one or more objects. So it has to be:

 $YTid = $banner_data['items'][0]->id;

This way you grab 'id' from the first item in the items-array.

BTW: learning to debug is crucial to learning to code. If you decode the json and then print the outcome you can see the structure of the array, which could have helped you to find the problem, like:

$banner_data = json_decode($banner_data, true);
var_dump($banner_data);

Upvotes: 1

Related Questions