我知道这可能已经在某个地方得到了解答,但在查看并查看了许多问题/答案和其他网站之后,我无法找到合适的答案.
我正在尝试创建一个页面,它将显示来自Youtube的一些视频.它将显示图像和标题.我已经设法做了这两个,虽然我的标题有问题.使用我正在使用的代码,它在加载时非常慢.我假设因为加载实际网站只是为了得到标题.
这就是我目前使用的标题.
function get_youtube_id($url){
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
return $my_array_of_vars['v'];
}
function get_youtube_title($video_id){
$url = "http://www.youtube.com/watch?v=".$video_id;
$page = file_get_contents($url);
$doc = new DOMDocument();
$doc->loadHTML($page);
$title_div = $doc->getElementById('eow-title');
$title = $title_div->nodeValue;
return $title;
}
Run Code Online (Sandbox Code Playgroud)
那么,如何通过id获得youtube标题的最佳方式.我的代码确实有效,但它也使页面加载速度非常慢.
谢谢
小智 6
这是一个使用PHP而没有库的简单方法.YouTube已经允许您以JSON格式检索视频详细信息,因此您只需要一个简单的功能:
function get_youtube_title($ref) {
$json = file_get_contents('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' . $ref . '&format=json'); //get JSON video details
$details = json_decode($json, true); //parse the JSON into an array
return $details['title']; //return the video title
}
Run Code Online (Sandbox Code Playgroud)
功能参数是视频ID.您还可以添加第二个参数,询问特定的详细信息并更改函数名称,以便您可以从JSON中检索任何您想要的数据.
编辑:
如果您想从返回的视频详细信息中检索任何信息,可以使用此功能:
function get_youtube_details($ref, $detail) {
if (!isset($GLOBALS['youtube_details'][$ref])) {
$json = file_get_contents('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' . $ref . '&format=json'); //get JSON video details
$GLOBALS['youtube_details'][$ref] = json_decode($json, true); //parse the JSON into an array
}
return $GLOBALS['youtube_details'][$ref][$detail]; //return the requested video detail
}
Run Code Online (Sandbox Code Playgroud)
如果您请求有关同一视频的不同详细信息,则返回的JSON数据将存储在$GLOBALS阵列中以防止必要的调用file_get_contents.
此外,allow_url_fopen必须在您php.ini的file_get_contents工作中,这可能是共享主机上的问题.