[PHP] 유튜브 API

2020. 3. 20. 12:04PHP

<?
/*
search
id - 검색 요청에 일치하는 리소스를 고유하게 식별하는 데 사용할 수 있는 정보를 포함합니다.
snippet - 제목이나 설명 등 검색결과에 대한 기본 세부정보를 포함합니다. 예를 들어, 검색결과가 동영상인 경우 제목은 동영상의 제목이고 설명은 동영상의 설명입니다.
videos
snippet - 동영상의 제목, 설명, 카테고리 등 동영상에 대한 기본 세부정보를 포함합니다.
contentDetails - 동영상의 길이 및 가로 세로 비율 등 동영상 콘텐츠에 대한 정보를 포함합니다.
status - 동영상의 업로드, 처리, 개인정보 보호 상태에 대한 정보를 포함합니다.
statistics - 동영상에 대한 통계를 포함합니다.
player - 내장 플레이어에서 동영상을 재생하기 위해 사용하려는 정보를 포함합니다.
topicDetails - 동영상과 관련된 Freebase 주제에 대한 정보를 요약합니다.
recordingDetails - 동영상이 녹화된 위치, 날짜, 주소에 대한 정보를 요약합니다.
fileDetails - 파일의 해상도, 기간, 오디오 및 동영상 코덱, 스트림 전송률 등 YouTube로 업로드한 동영상 파일에 대한 정보를 요약합니다. 이 데이터는 동영상 소유자만 검색할 수 있습니다.
suggestions - 업로드한 동영상의 동영상 품질이나 메타데이터를 향상시키기 위한 추천을 식별하는 제안을 요약합니다. 이 데이터는 동영상 소유자만 검색할 수 있습니다.
*/

$apiKey = '~~~~~~~~~~~~~~~~~~~~'; // API KEY
$channelId = '~~~~~~~~~~~~~~~~~~'; // 채널 ID
$url1 = 'https://www.googleapis.com/youtube/v3/search';
$url2 = 'https://www.googleapis.com/youtube/v3/videos';

function ytData($url, $param = array()){
	$url = $url.'?'.http_build_query($param, '', '&');
	$ch = curl_init();

	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	$response = curl_exec($ch);

	curl_close($ch);
	$data = json_decode($response,true);

	return $data['items'];
}

// SONA TV 채널 리스트
$data = array(
	'part' => 'snippet',
	'channelId' => $channelId,
	'maxResults' => '20',
	'order' => 'date',
	'type' => 'video',
	'key' => $apiKey
);
$results = ytData($url1,$data);

foreach($results as $val) {
	$data2 = array();
	$data2 = array(
		'part' => 'snippet',
		'id' => $val['id']['videoId'],
		'key' => $apiKey
	);
	$results2 = ytData($url2,$data2);
//	$results2[0]['snippet']['title'] 제목
//	$results2[0]['snippet']['publishedAt'] 날짜
//	$results2[0]['snippet']['thumbnails']['high']['url'] 썸네일이미지
//	$results2[0]['snippet']['channelTitle'] 채널이름

	$data3 = array();
	$data3 = array(
		'part' => 'statistics',
		'id' => $val['id']['videoId'],
		'key' => $apiKey
	);
	$results3 = ytData($url2,$data3);
//	$results3[0]['statistics']['viewCount'] 조회수

	$data4 = array(
		'part' => 'contentDetails',
		'id' => $val['id']['videoId'],
		'key' => $apiKey
	);
	$results4 = ytData($url2,$data4);
//	$results4[0]['contentDetails']['duration'] 영상길이
}
?>