如何使用PHP从视频网址中检索YouTube视频详细信息?

Ahm*_*uad 23 php youtube-api

使用PHP,我如何从YouTube视频网址获取标题,描述,缩略图等视频信息,例如

http://www.youtube.com/watch?v=B4CRkpBGQzU
Run Code Online (Sandbox Code Playgroud)

Nav*_*ngh 36

您可以通过两种格式从youtube oembed接口获取数据:XML和JSON

接口地址:http://www.youtube.com/oembed?url = youroutubeurl&format = json

使用此PHP函数来获取数据

 function get_youtube($url){

 $youtube = "http://www.youtube.com/oembed?url=". $url ."&format=json";

 $curl = curl_init($youtube);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 $return = curl_exec($curl);
 curl_close($curl);
 return json_decode($return, true);

 }

$url = // youtube video url 

// Display Data 
print_r(get_youtube($url));
Run Code Online (Sandbox Code Playgroud)

不要忘记启用extension=php_curl.dll 你的php.ini


But*_*rra 15

这将返回有关视频的元数据:

http://www.youtube.com/oembed?url={videoUrlHere}&format=json

使用您的示例,调用:

http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=B4CRkpBGQzU&format=json

返回以下内容,您可以使用PHP进行消化和解析:

{
    "provider_url": "http:\/\/www.youtube.com\/",
    "thumbnail_url": "http:\/\/i3.ytimg.com\/vi\/B4CRkpBGQzU\/hqdefault.jpg",
    "title": "Joan Osborne - One Of Us",
    "html": "\u003ciframe width=\"459\" height=\"344\" src=\"http:\/\/www.youtube.com\/embed\/B4CRkpBGQzU?fs=1\u0026feature=oembed\" frameborder=\"0\" allowfullscreen\u003e\u003c\/iframe\u003e",
    "author_name": "jzsdhk",
    "height": 344,
    "thumbnail_width": 480,
    "width": 459,
    "version": "1.0",
    "author_url": "http:\/\/www.youtube.com\/user\/jzsdhk",
    "provider_name": "YouTube",
    "type": "video",
    "thumbnail_height": 360
}
Run Code Online (Sandbox Code Playgroud)


OCT*_*RAM 5

另一个可能有用的URL API是:https : //www.youtube.com/get_video_info?video_id=B4CRkpBGQzU

video_id是youTube的“ v”参数。结果是URL编码格式的字典(key1 = value1&key2 = value2&...)

这是长期未记录的API,因此开发人员应自行研究。我知道“状态”(确定/失败),“错误代码”(在我的实践中为100和150),“原因”(错误的字符串描述)。我这样获取持续时间(“ length_seconds”),因为oEmbed不会提供此信息(奇怪,但为true),而且我几乎不鼓励每个雇主从youTube获取密钥以使用官方API