Getting viewCount from XML [duplicate]

2019-03-07 02:25发布

问题:

This question already has an answer here:

  • Get XML Attribute with SimpleXML 3 answers

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.