Getting viewCount from XML [duplicate]

折月煮酒 提交于 2019-12-02 23:37:31

问题


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;

Any help is greatly appreciated.


回答1:


For other people: the OP wants to access the <yt:statistics favoriteCount="0" viewCount="301" /> node that is a child of <entry> node.

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'));

You will see this:

array(1) {
  [0] =>
  class SimpleXMLElement#13 (1) {
    public $@attributes =>
    array(2) {
      'favoriteCount' =>
      string(1) "0"
      'viewCount' =>
      string(3) "301"
    }
  }
}

edit:

Final code will look like this:

$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;

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.



来源:https://stackoverflow.com/questions/17180080/getting-viewcount-from-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!