使用 SimpleXML 获取 XML 属性

2022-01-19 00:00:00 youtube-api php simplexml

我正在尝试获取 $xml->entry->yt:statistics->attributes()->viewCount 属性,并且我尝试了一些使用 SimpleXML 的东西,我真的无法让它工作!

I'm trying to get the $xml->entry->yt:statistics->attributes()->viewCount attribute, and I've tried some stuff with SimpleXML, and I can't really get it working!

尝试 #1

<?php
$xml = simplexml_load_file("http://gdata.youtube.com/feeds/api/videos?author=Google");
echo $xml->entry[0]->yt:statistics['viewCount'];
?>

尝试 #2

<?php
$xml = simplexml_load_file("http://gdata.youtube.com/feeds/api/videos?author=Google");
echo $xml->entry[0]->yt:statistics->attributes()->viewCount;
?>

这两个都返回空白,虽然 SimpleXML 正在工作,但我试图获取提要的标题,结果成功了!

Both of which return blank, though SimpleXML is working, I tried to get the feed's title, which worked!

有什么想法吗?

我查看了 SO 和其他网站上的大量其他示例,但不知何故这不起作用?PHP 是否将 ':' 识别为截断,还是我只是在做一些愚蠢的事情?

I've looked at loads of other examples on SO and other sites, but somehow this isn't working? does PHP recognize the ':' to be a cut-off, or am I just doing something stupid?

谢谢,任何回复都非常感谢!

Thank you, any responses greatly appreciated!

推荐答案

如果你只想获取一个 youtube 视频的观看次数,那么你必须指定视频 ID.youtube ID 位于每个视频网址中.例如http://www.youtube.com/watch?v=ccI-MugndOU"所以 id 是 ccI-MugndOU.为了获得观看次数,请尝试以下代码

If you just want to get the viewcount of a youtube video then you have to specify the video ID. The youtube ID is found in each video url. For example "http://www.youtube.com/watch?v=ccI-MugndOU" so the id is ccI-MugndOU. In order to get the viewcount then try the code below

$sample_video_ID = "ccI-MugndOU";
$JSON = file_get_contents("http://gdata.youtube.com/feeds/api/videos?q={$sample_video_ID}&alt=json");
$JSON_Data = json_decode($JSON);
$views = $JSON_Data->{'feed'}->{'entry'}[0]->{'yt$statistics'}->{'viewCount'};
    echo $views;

相关文章