【问题标题】:Getting viewCount from XML [duplicate]从 XML 获取 viewCount [重复]
【发布时间】:2013-06-18 22:27:50
【问题描述】:

我目前正在使用 YouTube API 表单 Google,我正在尝试获取“viewCount”数组。我已经尝试过了,完全没有运气。 Here 是我当前使用的链接。

我以前试过这个,但一点运气都没有。

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

非常感谢任何帮助。

【问题讨论】:

    标签: php xml youtube-api simplexml xml-namespaces


    【解决方案1】:

    对于其他人:OP 想要访问 <yt:statistics favoriteCount="0" viewCount="301" /> 节点,它是 <entry> node 的子节点。

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

    【讨论】:

    • 虽然可以使用 xpath 吗?
    • @IamGretar 我不明白上述问题。在第三行中,您可以看到调用 xpath 方法并且它有效。只需执行此代码,您就会看到。
    猜你喜欢
    • 1970-01-01
    • 2014-01-10
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 2014-04-10
    • 1970-01-01
    相关资源
    最近更新 更多