您的服务器的 allow_url_fopen 已禁用(我的也是如此)。我感觉到你的痛苦。这就是我所做的。
尝试使用cURL,但使用 YouTube 的 v2 api 以 json 格式返回您的数据。您可以通过将该数据附加到 url 的末尾来做到这一点。
?v=2&alt=json
您没有发布如何获取 YouTube ID,这可能是问题的一部分(尽管您的示例网址确实有效)。所以以防万一,我还发布了一个简单的函数来从 YouTube 视频 url 中检索 ID。
function get_youtube_id($url) {
$newurl = parse_url($url);
return substr($newurl['query'],2);
}
好的,现在假设您有视频 ID,您可以为要返回的每个字段运行以下函数。
// Grab JSON and format it into PHP arrays from YouTube.
// Options defined in the switch. No option returns entire array
// Example of what the returned JSON will look like, pretty, here:
// http://gdata.youtube.com/feeds/api/videos/dQw4w9WgXcQ?v=2&alt=json&prettyprint=true
function get_youtube_info ( $vid, $info ) {
$youtube = "http://gdata.youtube.com/feeds/api/videos/$vid?v=2&alt=json";
$ch = curl_init($youtube);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
//If $assoc = true doesn't work, try:
//$output = json_decode($output, true);
$output = json_decode($output, $assoc = true);
//Add the ['feed'] in if it exists.
if ($output['feed']) {
$path = &$output['feed']['entry'];
} else {
$path = &$output['entry'];
}
//set up a switch to return various data bits to return.
switch($info) {
case 'title':
$output = $path['title']['$t'];
break;
case 'description':
$output = $path['media$group']['media$description']['$t'];
break;
case 'author':
$output = $path['author'][0]['name'];
break;
case 'author_uri':
$output = $path['author'][0]['uri'];
break;
case 'thumbnail_small':
$output = $path['media$group']['media$thumbnail'][0]['url'];
break;
case 'thumbnail_medium':
$output = $path['media$group']['media$thumbnail'][2]['url'];
break;
case 'thumbnail_large':
$output = $path['media$group']['media$thumbnail'][3]['url'];
break;
default:
return $output;
break;
}
return $output;
}
$url = "http://www.youtube.com/watch?v=oHg5SJYRHA0";
$id = get_youtube_id($url);
echo "<h3><a href=" . $url . ">" . get_youtube_info($id, 'title') . "</a></h3>"; //echoes the title
echo "<p><a href=" . $url . "><img style='float:left;margin-right: 5px;' src=" . get_youtube_info($id, 'thumbnail_small') . " /></a>" . get_youtube_info($id, 'description') . "</p>"; //echoes the description
echo "<br style='clear:both;' /><pre>";
echo print_r(get_youtube_info($id));
echo "</pre>";