从 XML 获取 viewCount [英] Getting viewCount from XML
问题描述
我目前正在使用 Google 的 YouTube API,我正在尝试获取"viewCount"数组.我已经尝试过这个,但完全没有运气.这里是我当前的链接使用.
I'm currently using the YouTube API form Google and I'm trying to get the "viewCount" array. I've tried this already with no luck at all. Here is the link that I'm currently using.
我之前试过这个,完全没有运气.
I tried this before with no luck at all.
$url = 'http://gdata.youtube.com/feeds/api/users/gudjondaniel/uploads?max-results=1';
$source = file_get_contents($url);
$xml = new SimpleXMLElement($source);
$title = $xml->entry->viewCount;
非常感谢任何帮助.
推荐答案
对于其他人:OP 想要访问 <yt:statistics favoriteCount="0" viewCount="301"/>
节点是
.
For other people: the OP wants to access the <yt:statistics favoriteCount="0" viewCount="301" />
node that is a child of <entry> node
.
试试这个(xpath):
Try this (xpath):
$file = simplexml_load_file('http://gdata.youtube.com/feeds/api/users/gudjondaniel/uploads?max-results=1');
var_dump($file->xpath('//yt:statistics'));
你会看到:
array(1) {
[0] =>
class SimpleXMLElement#13 (1) {
public $@attributes =>
array(2) {
'favoriteCount' =>
string(1) "0"
'viewCount' =>
string(3) "301"
}
}
}
最终代码如下:
$file = simplexml_load_file('http://gdata.youtube.com/feeds/api/users/gudjondaniel/uploads?max-results=1');
$xpath = $file->xpath('//yt:statistics');
$attrs = $xpath[0]->attributes();
echo (string) $attrs->viewCount;
顺便说一下,SimpleXMLElement 是一个胡言乱语的 PHP 工具 - 正如您所看到的 - 几乎不可能访问像 <yt:statistics>
这样的元素.其他平台使用 xpath 作为标准.
By the way, SimpleXMLElement is a gibberish-PHP tool that - as you can see - makes it hardly possible to access element like <yt:statistics>
. Other platforms use xpath as a standard.
这篇关于从 XML 获取 viewCount的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!