我正在尝试根据任何 youtube URL 获取 youtube id。我生成了一个 key 。事情是基于这个 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>
关于php - 获取基于 URL API V3 的 youtube ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30846097/