ถ้าคุณอยากจะทำ website ที่แสดงเฉพาะ Video ที่เกี่ยวกับ สิงโตนำโชคโดยเฉพาะ จะทำยังไงล่ะ? พระเอกของงานนี้ Google APIs Client ครับ เข้าไป Download ได้ที่นี่เลย https://developers.google.com/discovery/libraries
Download ตัว Google APIs Client Library for PHP (beta) แล้ว upload ขึ้น Server ของเรา ภายในจะประกอปไปด้วย Directory ต่างๆ แล้วเราก็ไปที่ https://console.developers.google.com เพื่อเปิดใช้งาน Youtube API ครับ
จัดการสร้าง public api access ซะ เพื่อนำ api key มา config ในโปรแกรมของเรา หลังจากนั้นเราก็เขียน PHP ขึ้นมาตัวนึงไว้สำหรับดึงข้อมูลมาแสดง
<!DOCTYPE html>
<html>
<head>
<title>TWIN SYNERGY CO., LTD. | We are not waiting for future. "We create the future"</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php
require_once $_SERVER["DOCUMENT_ROOT"].'/src/Google_Client.php';
require_once $_SERVER["DOCUMENT_ROOT"].'/src/contrib/Google_YouTubeService.php';
$DEVELOPER_KEY = 'ใส่ APIs Client Key ของ Youtube ที่นี่';
$client = new Google_Client();
$client->setDeveloperKey($DEVELOPER_KEY);
$youtube = new Google_YoutubeService($client);
try {
$searchResponse = $youtube->search->listSearch('id,snippet', array(
'q' => 'ออฟ ปองศักดิ์',
'maxResults' => 50,
'order' => $_GET['order'],// ค่าของ order จะมีการเรียงลำดับแบบ date คือเรียงตามวันที่ , videoCount คือตามจำนวนผู้ชม , rating คือตามความฮิตของ video นั้นๆ , relevance คือตามปรกติ
'pageToken' => $_GET['pageToken'],//ค่า page token คือจะแสดงถ้าถัดไป หรือหน้าก่อนหน้านี้ สามารถ ดูได้จาก result ที่ดึงออกมาได้ เช่น หน้าถัดไป คือ CDIQAA ก็แทนค่าลงไป
));
$videos = array();
$videos['playList'] = array();
$videos['pageToken'] = $searchResponse['nextPageToken'];
foreach ($searchResponse['items'] as $searchResult) {
switch ($searchResult['id']['kind']) {
case 'youtube#video':
/*
ถ้าอยากรู้ว่า ค่าในตัวแปรมีอะไรบ้างก็จัดการ var_dump($searchResult); ออกมาดูซะ
echo '<pre>';
var_dump($searchResult);
echo '</pre>';
*/
echo '<iframe width="560" height="315" src="//www.youtube.com/embed/'.$searchResult['id']['videoId'].'" frameborder="0" allowfullscreen></iframe><br/>Channel: '.$searchResult['snippet']['channelTitle'].'<br/>Title: '.$searchResult['snippet']['title'].'<br/>Desc: '.$searchResult['snippet']['description'].'<hr>';
break;
}
}
} catch (Google_ServiceException $e) {
$htmlBody .= sprintf('A service error occurred: %s',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('An client error occurred: %s',
htmlspecialchars($e->getMessage()));
}
?>
</body>
</html>