当视频ID以( - )减号开头时,PHP youtube xml feed reeor

时间:2014-02-25 03:51:55

标签: php youtube youtube-api

我正在使用此代码来获取YouTube视频信息,并且它正常工作,直到我尝试任何视频时出现错误( - )减去示例:-VF0JwxQqcA

<?php
    //The Youtube"s API url
    define('YT_API_URL', 'http://gdata.youtube.com/feeds/api/videos?q=');
    //Change below the video id.
    $video_id2 = "$video_id2";
    //Using cURL php extension to make the request to youtube API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, YT_API_URL . $video_id2);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //$feed holds a rss feed xml returned by youtube API
    $feed = curl_exec($ch);
    curl_close($ch);
    //Using SimpleXML to parse youtube"s feed
    $xml = simplexml_load_string($feed);
    $entry = $xml->entry[0];
    //If no entry whas found, then youtube didn"t find any video with specified id
    if(!$entry) exit('Error: no video with id "' . $video_id2 . '" whas found. Please specify the id of a existing video.');
    $media = $entry->children("media", true);
    $group = $media->group;

    $title = $group->title;//$title: The video title

    $desc = $group->description;//$desc: The video description
    $news_images = $group->thumbnail[0];//There are 4 thumbnails, the first one (index 0) is the largest.
    //$thumb_url: the url of the thumbnail. $thumb_width: thumbnail width in pixels.
    //$thumb_height: thumbnail height in pixels. $thumb_time: thumbnail time in the video
    list($thumb_url) = $news_images->attributes();
    $content_attributes = $group->content->attributes();
    //$vid_duration: the duration of the video in seconds. Ex.: 192.
    $vid_duration = $content_attributes["duration"];
    //$duration_formatted: the duration of the video formatted in "mm:ss". Ex.:01:54
    $source= "http://i.ytimg.com/vi/$video_id2/mqdefault.jpg";
?>

错误将是:错误:找不到ID为“-VF0JwxQqcA”的视频。请指定现有视频的ID。

请帮忙吗? 感谢

1 个答案:

答案 0 :(得分:1)

问题是您正在使用搜索Feed,因此,当您打算排除该字符串时,YouTube会使用以“ - ”开头的视频来解释您的通话。但是,如果您已经知道视频ID,则根本不应该使用搜索Feed ...这真的是要搜索关键字。如果您知道videoID,则应使用此Feed:

https://gdata.youtube.com/feeds/api/videos/-VF0JwxQqcA

(换句话说,摆脱'q'URL参数,然后将videoID作为URL路径的一部分附加。)

您可能需要稍微更改解析器,但这是一种更可靠的方式来返回视频数据。

我是否还建议考虑转向API的v3?您可以使用这样的端点:

https://www.googleapis.com/youtube/v3/videos?part=id,snippet&id=-VF0JwxQqcA&key={YOUR_API_KEY}

返回的数据将是JSON,这更容易解析,并且您不必担心在弃用v2时需要更改应用程序。对于视频资源,v3返回的信息也更完整。