获取基于URL API V3的YouTube ID?

时间:2015-06-15 13:12:13

标签: php youtube

我正在尝试根据任何youtube网址获取youtube ID。我生成了一把钥匙。事情基于这个id我想要检索标题和描述,如下面的URL

https://www.googleapis.com/youtube/v3/videos?part=snippet&id=MY_ID&key=MY_KEY&alt=json&prettyprint=true

现在我正在使用PHP从ULR中提取视频ID,然后使用我在stackoverflow中找到的方法将其传递给上面的链接

$url_string = parse_url($url, PHP_URL_QUERY);
parse_str($url_string, $args);
return isset($args['v']) ? $args['v'] : false;

这种方法每次都没有用。我也试过一个正则表达式,但我遇到了同样的问题。另外,我在https://developers.google.com/youtube/v3/docs/搜索。任何建议!!

感谢。

1 个答案:

答案 0 :(得分:0)

沿着这些行的某些内容将根据网址(将$url设置为相应的网址)获取YouTube电影的标题和说明:

<?php

$url="https://www.youtube.com/watch?v=7SpNHMwwID4";
parse_str(parse_url($url)['query'], $args);

$googleAPI = "https://www.googleapis.com/youtube/v3/videos";
$googleAPI .= "?part=snippet";
$googleAPI .= "&id=" . $args['v'];
$googleAPI .= "&key={YOUR-API-KEY}";

$JSON = file_get_contents($googleAPI);
$videoResponse = json_decode($JSON, true);

?>

<!doctype html>
<html>
  <head>
    <title>Video information</title>
  </head>
  <body>
  Title: <?= $videoResponse['items'][0]['snippet']['title']; ?><br/>
  Description: <?= $videoResponse['items'][0]['snippet']['description']; ?>
  </body>
</html>

您可以使用YouTube PHP客户端库执行类似操作(再次适当地设置$url):

<?php

require_once 'Google/autoload.php';
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';

$client = new Google_Client();
$client->setDeveloperKey('{YOUR-API-KEY}');
$youtube = new Google_Service_YouTube($client);

$url="https://www.youtube.com/watch?v=7SpNHMwwID4";
parse_str(parse_url($url)['query'], $args);

$videoResponse = $youtube->videos->listVideos('snippet', array(
    'id' => $args['v']
));

$title = $videoResponse['items'][0]['snippet']['title'];
$description = $videoResponse['items'][0]['snippet']['description'];
?>

<!doctype html>
<html>
  <head>
    <title>Video information</title>
  </head>
  <body>
  Title: <?= $title ?><br/>
  Description: <?= $description ?>
  </body>
</html>