在我的一个应用程序中,我保存了一个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-get-contents:无法打开流: HTTP请求失败!需要HTTP/1.0 402付款
文件名:model/webs.php
行号: 128
发布于 2012-03-12 17:33:35
在file_get_contents之前使用error control operators可能是可行的。
类似于:
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
}发布于 2012-03-12 17:44:06
对远程URL使用file_get_contents()是不安全的。在YouTube API2.0中使用cURL:
$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.
}发布于 2013-04-01 04:02:47
这是我的解决方案。它很短。
$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];https://stackoverflow.com/questions/9664482
复制相似问题