如何从搜索中获取第一个 YouTube 视频的网址


How to get the URL of the first YouTube video from a search?

我有一个包含电影表的网站,我想显示电影的预告片。为了做到这一点,是否可以从YouTube搜索中获取顶级YouTube视频的URL?

由于输入"[电影名称]预告片"在大多数情况下效果很好,并且预告片通常是顶部视频,因此很容易。

在不同的主题上,如果选择的视频不正确,让用户修改视频的最佳方法是什么?使用投票系统,因此至少需要 4-5 票才能更改视频。

这是我使用

谷歌的YouTube API在我的旧网站上使用的YouTube搜索

<?php
// Call set_include_path() as needed to point to your client library.
  require_once ('video/Google_Client.php');
  require_once ('video/Google_YouTubeService.php');
  /* Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
  Google APIs Console <http://code.google.com/apis/console#access>
  Please ensure that you have enabled the YouTube Data API for your project. */
  $DEVELOPER_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
  $client = new Google_Client();
  $client->setDeveloperKey($DEVELOPER_KEY);
  $youtube = new Google_YoutubeService($client);
  try {
    $searchResponse = $youtube->search->listSearch('id,snippet', array(
      'q' => $_POST['query'],
      'maxResults' => '48',
    ));
    $videos = '';
    $channels = '';
    foreach ($searchResponse['items'] as $searchResult) {
      switch ($searchResult['id']['kind']) {
        case 'youtube#video':
          $videos .=  $searchResult;

          break;
       }
    }
   } catch (Google_ServiceException $e) {
    $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
  } catch (Google_Exception $e) {
    $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
  }

echo print_r($videos);
?>

我使用了一个表单来发布搜索查询(请注意 $_POST['search'] 变量,这将是要搜索的字符串,在您的情况下是电影名称)