获取YouTube视频的标题,说明和观看次数

Kak*_*aka 6 php

$youtube = simplexml_load_file('http://gdata.youtube.com/feeds/api/videos/wGG543FeHOE?v=2');
$title = $youtube->title;
Run Code Online (Sandbox Code Playgroud)

这得到了标题.但我怎么能得到viewcount和描述?尝试$youtube->description;和$youtube->views;

Bac*_*ash 22

我建议你使用JSON输出而不是XML输出.

您可以通过将alt=json参数添加到您的网址来获取它:

http://gdata.youtube.com/feeds/api/videos/wGG543FeHOE?v=2&alt=json
Run Code Online (Sandbox Code Playgroud)

然后你必须加载json并解析它:

<?php
$json_output = file_get_contents("http://gdata.youtube.com/feeds/api/videos/wGG543FeHOE?v=2&alt=json");
$json = json_decode($json_output, true);

//This gives you the video description
$video_description = $json['entry']['media$group']['media$description']['$t'];

//This gives you the video views count
$view_count = $json['entry']['yt$statistics']['viewCount'];

//This gives you the video title
$video_title = $json['entry']['title']['$t'];
?>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

UPDATE

要查看JSON输出有哪些变量,将prettyprint=true参数添加到URL并在浏览器中打开它,它将美化JSON输出以使其更易于理解:

http://gdata.youtube.com/feeds/api/videos/wGG543FeHOE?v=2&alt=json&prettyprint=true
Run Code Online (Sandbox Code Playgroud)

您可以直接编写,而不是浏览URL

echo "<pre>";
print_r($json);
echo "</pre>";
Run Code Online (Sandbox Code Playgroud)

后

$json = json_decode($json_output, true);
Run Code Online (Sandbox Code Playgroud)

它将打印格式化的JSON输出

  • @Kaka试试`if(($ json_output = file_get_contents('http://gdata.youtube.com/feeds/api/videos/INVALID_ID?v=2&alt=json'))){something ...} else {echo'错误'; }` (4认同)

小智 5

我的代码:

$vId = "Jer8XjMrUB4";
$gkey = "AIzaSyCO5lIc_Jlrey0aroqf1cHXVF1MUXLNuR0";

$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=".$vId."&key=".$gkey."");


$data = json_decode($dur, true);
foreach ($data['items'] as $rowdata) {
     $vTime = $rowdata['contentDetails']['duration'];
     $desc = $rowdata['snippet']['description'];
}


$interval = new DateInterval($vTime);
$vsec = $interval->h * 3600 + $interval->i * 60 + $interval->s;

if($vsec > 3600)
    $vsec = gmdate("H:i:s", $vsec);
else
    $vsec = gmdate("i:s", $vsec);

echo $vsec."--".$desc;
Run Code Online (Sandbox Code Playgroud)

结果:

02:47-在备受赞誉的全球红极一时X战警之后: