用PHP获取YouTube视频标题


Get YouTube video title in PHP

在我的一个应用程序中,我正在保存YouTube视频的id;A4fR3sDprOE";。我必须在应用程序中显示它的标题。我得到了下面的代码来获得它的标题,而且它运行得很好。

现在的问题是,如果出现任何错误(在删除视频的情况下),PHP将显示一个错误。我添加了一个条件。但它仍然显示出错误。

foreach($videos as $video) {
    $video_id = $video->videos;
    if($content=file_get_contents("http://youtube.com/get_video_info?video_id=".$video_id)) {
        parse_str($content, $ytarr);
        $myvideos[$i]['video_title']=$ytarr['title'];
    }
    else
        $myvideos[$i]['video_title']="No title";
    $i++;
}
return $myvideos;

在出现错误的情况下,它会随着以下内容而消亡:

严重性:警告

消息:file_get_contents(http://youtube.com/get_video_info?video_id=A4fR3sDprOE)[函数.file获取内容]:无法打开流:HTTP请求失败!HTTP/1.0 402要求支付

文件名:models/webs.php

行号:128

将file_get_contents()与远程URL一起使用是不安全的。使用cURL代替YouTube API 2.0:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://gdata.youtube.com/feeds/api/videos/' . $video_id);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
if ($response) {
    $xml   = new SimpleXMLElement($response);
    $title = (string) $xml->title;
} else {
    // Error handling.
}

这是我的解决方案。它很短。

$id = "VIDEO ID";
$videoTitle = file_get_contents("http://gdata.youtube.com/feeds/api/videos/${id}?v=2&fields=title");
preg_match("/<title>(.+?)<'/title>/is", $videoTitle, $titleOfVideo);
$videoTitle = $titleOfVideo[1];

在file_get_contents之前使用错误控制运算符可能会起作用。

类似于:

if($content = @file_get_contents("http://youtube.com/get_video_info?video_id=" . $video_id))

它应该删除该错误,并使用它在if语句中返回false。

否则,您可以只使用try/catch语句(请参阅异常):

try{
    // Code
}
catch (Exception $e){
    // Else code
}

我相信您的托管提供商出于安全目的禁用了file_get_contents。您应该使用cURL。

<?php
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://youtube.com/get_video_info?video_id=" . $video_id);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    /* Parse YouTube's response as you like below */
?>

尝试:

// Use @ to suppress warnings
$content = @file_get_contents("http://youtube.com/get_video_info?video_id=" . $video_id);
if($content===FALSE) {
    .. Handle error here
}
else{
    ..The rest of your code
}

我想补充一点,这里看到的特定错误(HTTP 402-Payment Required,这是服务器通常没有实现的HTTP状态代码)是YouTube在确定;过度的";流量一直来自您的IP地址(或IP地址范围——他们确实喜欢频繁地阻止OVH的IP地址范围[1][2])

因此,如果您以编程方式(使用PHP或其他方式)访问youtube.com(而不是API),您最终可能会发现自己遇到了这个错误。YouTube通常从向来自"用户"的请求呈现CAPTCHA开始;"过度交通";IP地址,但如果你没有完成它们(你的PHP脚本不会完成),他们会切换到这些毫无帮助的402响应,基本上没有追索权-YouTube没有客户支持台可以打电话,如果你因为IP地址屏蔽而无法访问他们的任何网站,你联系他们的机会就更小了。

其他参考资料:
http://productforums.google.com/forum/#!主题/youtube/tR4WkNBPnUohttp://productforums.google.com/forum/?fromgroups=#!主题/youtube/179aboankVg

我的解决方案是:

$xmlInfoVideo = simplexml_load_file("http://gdata.youtube.com/feeds/api/videos/" . $videoId . "?v=2&fields=title");
foreach($xmlInfoVideo->children() as $title) {
    $videoTitle = strtoupper((string) $title); 
}

这就是视频的标题。