Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active August 16, 2022 13:30
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save james2doyle/9210212 to your computer and use it in GitHub Desktop.
Save james2doyle/9210212 to your computer and use it in GitHub Desktop.
A PHP function to get youtube video title by just passing the video ID
<?php
function youtube_title(string $id) {
// $id = 'YOUTUBE_ID';
$API_KEY = "YOUR-API-KEY";
$videoList = @json_decode(@file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=snippet&id={$id}&key={$API_KEY}"));
// despite @ suppress, it will be false if it fails
if ($videoTitle) {
// look for that title tag and get the insides
preg_match("/<title>(.+?)<\/title>/is", $videoTitle, $titleOfVideo);
return $titleOfVideo[1];
} else {
return false;
}
// usage:
// $item = youtube_title('zgNJnBKMRNw');
}
@VDK
Copy link

VDK commented May 15, 2015

V3 API:

function youtube_title($id) {
// $id = 'YOUTUBE_ID';
// returns a single line of JSON that contains the video title. Not a giant request.
$videoTitle = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=".$id."&key=YOUR_API_KEY&fields=items(id,snippet(title),statistics)&part=snippet,statistics");
// despite @ suppress, it will be false if it fails
if ($videoTitle) {
$json = json_decode($videoTitle, true);

return $json['items'][0]['snippet']['title'];
} else {
return false;
}
}

@Cocomaniahack
Copy link

thanks fue de gran ayuda es muy facil

@MrWeb
Copy link

MrWeb commented Apr 21, 2020

It changed:

function youtube_title($id)
{
    $API_KEY   = "YOUR-API-KEY";
    $videoList = json_decode(file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=snippet&id={$id}&key={$API_KEY}"));

    //Image
    //$videoList->items[0]->snippet->thumbnails->default;

    //Title
    // $videoList->items[0]->snippet->title;
}

@james2doyle
Copy link
Author

@MrWeb thanks for the update

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment