Как получить полное описание видео с youtube с помощью Youtube API v3
Всех приветствую! Изначально задача была такая: Есть канал, и нужно получить название и описание каждого видео с этого канала. Нашел готовое решение: config.php
<?php
define('GOOGLE_API_KEY', 'PASTE_YOUR_API_KEY');
function getYTList($api_url = '') {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$arr_result = json_decode($response);
if (isset($arr_result->items)) {
return $arr_result;
} elseif (isset($arr_result->error)) {
//var_dump($arr_result); //this line gives you error info if you are not getting a video list.
}
}
index.php
<?php
require_once "config.php";
$arr_list = array();
if (array_key_exists('channel', $_GET) && array_key_exists('max_result', $_GET)) {
$channel = $_GET['channel'];
$url = "https://www.googleapis.com/youtube/v3/search?channelId=$channel&order=date&part=snippet&type=video&maxResults=". $_GET['max_result'] ."&key=". GOOGLE_API_KEY;
$arr_list = getYTList($url);
}
?>
<form method="get">
<p><input type="text" name="channel" placeholder="Enter Channel ID" value="<?php if(array_key_exists('channel', $_GET)) echo $_GET['channel']; ?>" required></p>
<p><input type="number" name="max_result" placeholder="Max Results" min="1" max="50" value="<?php if(array_key_exists('max_result', $_GET)) echo $_GET['max_result']; ?>" required></p>
<p><input type="submit" value="Submit"></p>
</form>
<?php
if (!empty($arr_list)) {
echo '<ul class="video-list">';
foreach ($arr_list->items as $yt) {
echo "<li>". $yt->snippet->title ." (". $yt->id->videoId .")</li>";
}
echo '</ul>';
if (isset($arr_list->nextPageToken)) {
echo '<input type="hidden" class="nextpagetoken" value="'. $arr_list->nextPageToken .'" />';
echo '<div id="loadmore">Load More</div>';
}
}
?>
<script>
var httpRequest, nextPageToken;
document.getElementById("loadmore").addEventListener('click', makeRequest);
function makeRequest() {
httpRequest = new XMLHttpRequest();
nextPageToken = document.querySelector('.nextpagetoken').value;
if (!httpRequest) {
alert('Giving up: Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var list = JSON.parse(this.responseText);
for (var i in list) {
if (list[i].title != undefined && list[i].id != undefined) {
var newElement = document.createElement('li');
newElement.innerHTML = '<li>' + list[i].title + '(' + list[i].id + ')</li>';
document.querySelector('.video-list').appendChild(newElement);
}
}
if (list[list.length - 1].nextPageToken != undefined) {
document.querySelector('.nextpagetoken').value = list[list.length - 1].nextPageToken;
} else {
var loadmore = document.getElementById("loadmore");
loadmore.parentNode.removeChild(loadmore);
}
}
};
httpRequest.open('GET', 'ajax.php?channel=<?php echo $_GET['
channel ']; ?>&max_result=<?php echo $_GET['
max_result ']; ?>&nextPageToken=' + nextPageToken, true);
httpRequest.send();
}
</script>
ajax.php
<?php
require_once "config.php";
$url = "https://www.googleapis.com/youtube/v3/search?channelId=". $_GET['channel'] ."&order=date&part=snippet&type=video&maxResults=". $_GET['max_result'] ."&pageToken=". $_GET['nextPageToken'] ."&key=". GOOGLE_API_KEY;
$arr_list = getYTList($url);
$arr_result = array();
if (!empty($arr_list)) {
foreach ($arr_list->items as $yt) {
array_push($arr_result, ['title' => $yt->snippet->title, 'id' => $yt->id->videoId]);
}
if (isset($arr_list->nextPageToken)) {
array_push($arr_result, ['nextPageToken' => $arr_list->nextPageToken]);
}
}
echo json_encode($arr_result);
Всё работает, вопросов нет. Немного пришлось изменить, так как нужен был всего один канал. Теперь хотелось бы узнать, как правильно запрашивать полное описание видео. В настоящее время описание обрезается троеточием.
Нашел опять таки готовое решение:
$string = file_get_contents("https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCuCQXqQLAQuTObCGlTYDE3w&maxResults=50&order=date&key=API_KEY_HERE&fields=nextPageToken,pageInfo,items(id(videoId),snippet(title,description,channelTitle,thumbnails(high(url))))");
$json_a = json_decode($string, true); foreach($json_a['items'] as $video)
{
$description = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=snippet&id={$video['id']['videoId']}&key=API_KEY_HERE");
$description = json_decode($description, true);
$description = $description['items'][0]['snippet']['description'];
}
но не могу понять, как теперь это реализовать на том, что уже имеется.