Get XML Attribute with SimpleXML

后端 未结 3 1300
予麋鹿
予麋鹿 2020-12-20 06:23

I\'m trying to get the $xml->entry->yt:statistics->attributes()->viewCount attribute, and I\'ve tried some stuff with SimpleXML, and I can\'t really

相关标签:
3条回答
  • 2020-12-20 06:56

    The yt: prefix marks that element as being in a different "XML namespace" from the rest of the document. You have to tell SimpleXML to switch to that namespace using the ->children() method.

    The line you were attempting should actually look like this:

    echo (string)$xml->entry[0]->children('yt', true)->statistics->attributes(NULL)->viewCount;
    

    To break this down:

    • (string) - this is just a good habit: you want the string contents of the attribute, not a SimpleXML object representing it
    • $xml->entry[0] - as expected
    • ->children('yt', true) - switch to the namespace with the local alias 'yt'
    • ->statistics - as expected
    • ->attributes(NULL) - technically, the attribute "viewCount" is back in the default namespace, because it is not prefixed with "yt:", so we have to switch back in order to see it
    • ->viewCount - running ->attributes() gives us nothing but attributes, which are accessed with ->foo not ['foo']
    0 讨论(0)
  • 2020-12-20 07:10

    If you just want to get the viewcount of a youtube video then you have to specify the video ID. The youtube ID is found in each video url. For example "http://www.youtube.com/watch?v=ccI-MugndOU" so the id is ccI-MugndOU. In order to get the viewcount then try the code below

    $sample_video_ID = "ccI-MugndOU";
    $JSON = file_get_contents("http://gdata.youtube.com/feeds/api/videos?q={$sample_video_ID}&alt=json");
    $JSON_Data = json_decode($JSON);
    $views = $JSON_Data->{'feed'}->{'entry'}[0]->{'yt$statistics'}->{'viewCount'};
        echo $views;
    
    0 讨论(0)
  • 2020-12-20 07:13

    I would use the gdata component from the zend framework. Is also available as a separate module, so you don't need to use the whole zend.

    0 讨论(0)
提交回复
热议问题