4
votes

I am trying to get a list of a user's latest videos/uploads. I am trying to get my head around this new v3 API, but I cannot find any properly working PHP code examples, not even on the dedicated YouTube API website.

I have a list of YouTube usernames, and I just want to simply get a list of their latest videos with video ID, title, thumbnail URL, etc. Basically in a foreach loop.

Any advice?

I have the following code, I need to make it work by the actual YouTube usernames.

$url = 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername=ferrariworld&key=ZZZZZZZZ';
$json = json_decode(file_get_contents($url), true);
foreach ($json as $item){
echo $item[0]['id'];
echo $item[0]['title'];
}
1
developers.google.com/apis-explorer/#p/youtube/v3/… See the forUsername attribute, it will give you the channel identifiers back. - naththedeveloper

1 Answers

2
votes

Use the channels endpoint with a forUsername attribute (see the documentation for the endpoint).

GET https://www.googleapis.com/youtube/v3/channels?part=id&forUsername={USERNAME}&key={YOUR_API_KEY}

It will give you this kind of response:

{
 "kind": "youtube#channelListResponse",
 "etag": "\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/7Q8DJLb6b2hwYAXUQLI3ftt3R8U\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 5
 },
 "items": [
  {

   "kind": "youtube#channel",
   "etag": "\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/pDjr9xPn51KtRM3gbMOq2aHBIbY\"",
   "id": "UCr3LuetcEeidWiuhxaw4B2g"
  }
 ]
}

The channel ID of that user can be found at items[0]['id'] if you convert the JSON to array.

As for your edit, you’re accessing the JSON object incorrectly. You need to use something like this.

if (array_key_exists('items', $json) && count($json['items']) === 1) {
    $item = $json['items'][0];

    $channelId = $item['id']; // The users channel ID.
}