用PHP获取youtube视频标题

ram*_*esh 2 php youtube-api youtube-javascript-api

在我的一个应用程序中,我正在保存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;
Run Code Online (Sandbox Code Playgroud)

如果出现错误,它会在以下情况下死亡

严重性:警告

消息:file_get_contents(http://youtube.com/get_video_info?video_id=A4fR3sDprOE)[function.file-get-contents]:无法打开流:HTTP请求失败!HTTP/1.0 402需要付款

文件名:models/webs.php

行号:128

请帮忙

Ger*_*osi 11

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.
}
Run Code Online (Sandbox Code Playgroud)


小智 6

这是我的解决方案.很短.

$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];
Run Code Online (Sandbox Code Playgroud)