Last active
August 16, 2022 13:30
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
} |
thanks fue de gran ayuda es muy facil
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;
}
@MrWeb thanks for the update
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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;
}
}