Getting viewCount from XML


Getting viewCount from XML

我目前正在使用YouTube API形式谷歌,我试图获得"viewCount"数组。我已经试过了,但一点都不成功。这是我目前正在使用的链接。

我以前试过,但一点都不成功。

$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想要访问<entry> node的子节点<yt:statistics favoriteCount="0" viewCount="301" />

试试这个(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作为标准。