获取基于网址 API V3 的 youtube ID


Get a youtube ID based on URL API V3?

我正在尝试根据任何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/中搜索。任何建议!!

谢谢。

类似这些内容将根据URL获取YouTube电影的标题和描述(设置为$url适当的URL):

<?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>