如何使用YouTube搜索引擎API?

时间:2015-03-05 10:17:30

标签: php youtube google-api-v3

我在Github上找到了一些关于YouTube API的示例,所以对于我的网站,我启用了Google开发者控制台的“YouTube Data API v3”,但是在将以下代码上传到我的网站后,我无法检索任何视频和我从浏览器控制台收到此错误:点击搜索按钮后出现“Failed to load resource: the server responded with a status of 500 (Internal Server Error)”。

这是我的search.php文件:

<?php

$htmlBody = <<<END
<form method="GET">
  <div>
    Search Term: <input type="search" id="q" name="q" placeholder="Enter Search Term">
  </div>
  <div>
    Max Results: <input type="number" id="maxResults" name="maxResults" min="1" max="50" step="1" value="25">
  </div>
  <input type="submit" value="Search">
</form>
END;

if ($_GET['q'] && $_GET['maxResults']) {
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';

  $DEVELOPER_KEY = 'my_api_key';

  $client = new Google_Client();
  $client->setDeveloperKey($DEVELOPER_KEY);

  $youtube = new Google_Service_YouTube($client);

  try {
    $searchResponse = $youtube->search->listSearch('id,snippet', array(
      'q' => $_GET['q'],
      'maxResults' => $_GET['maxResults'],
    ));

    $videos = '';
    $channels = '';
    $playlists = '';

    foreach ($searchResponse['items'] as $searchResult) {
      switch ($searchResult['id']['kind']) {
        case 'youtube#video':
          $videos .= sprintf('<li>%s (%s)</li>',
              $searchResult['snippet']['title'], $searchResult['id']['videoId']);
          break;
        case 'youtube#channel':
          $channels .= sprintf('<li>%s (%s)</li>',
              $searchResult['snippet']['title'], $searchResult['id']['channelId']);
          break;
        case 'youtube#playlist':
          $playlists .= sprintf('<li>%s (%s)</li>',
              $searchResult['snippet']['title'], $searchResult['id']['playlistId']);
          break;
      }
    }

    $htmlBody .= <<<END
    <h3>Videos</h3>
    <ul>$videos</ul>
    <h3>Channels</h3>
    <ul>$channels</ul>
    <h3>Playlists</h3>
    <ul>$playlists</ul>
END;
  } 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()));
  }
}
?>

<!doctype html>
<html>
  <head>
    <title>YouTube Search</title>
  </head>
  <body>
    <?=$htmlBody?>
  </body>
</html>

出了什么问题以及为什么我无法检索YouTube视频?

1 个答案:

答案 0 :(得分:0)

听起来你的脚本中有语法错误。 500错误是在服务器端问题阻止完成请求时返回的HTTP状态错误。该错误不太可能来自Youtube API。

我在该代码中没有看到明显的语法错误。您应该查看Apache / ngnix /其他Web服务器错误日志,然后从那里开始和/或发布错误。