0

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?

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

This has been a helpful answer overall but still hasn't fixed the problem! Thanks and i never thought of using a var_dump. This has really helped! In my other parts of code i seem to be able to use $stats_data = $data['entry']['yt$statistics'];
@ConorReid not resolved? Working just fine on my end. You have basically just provided a variable with absolutely no context there
So does it work now? I think johnh10 is right in his answer BTW, it has to be ->id since it's an object. I edited my answer.
1

Try this instead:

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

2 Comments

I just noticed you used true for the 2nd argument so json returns assoc arrays. Above code will work.
I ended up with conflicting code that was stopping it working. Sorry, it does work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.