Help parsing XML with DOMDocument

≡放荡痞女 提交于 2020-01-10 04:00:15

问题


I am trying to parse a youtube playlist field.

The URL is: http://gdata.youtube.com/feeds/api/playlists/664AA68C6E6BA19B?v=2

I need: Title, Video ID, and Default thumbnail.

I can easily get the title but I'm a little lost when it comes to the nested elements

        $data = new DOMDocument();
        if($data->load("http://gdata.youtube.com/feeds/api/playlists/664AA68C6E6BA19B?v=2"))
        {       
            foreach ($data->getElementsByTagName('entry') as $video)
            {
                $title = $video->getElementsByTagName('title')->item(0)->nodeValue;
                $id    = ??
                $thumb = ??                 
            }
        }

Here is the XML (I have stripped out the elements that are irrelevant for this example)

<entry gd:etag="W/&quot;AkYGSXc9cSp7ImA9Wx9VGEk.&quot;">    
    <title>A GoPro Weekend On The Ice</title>

    <media:group>
        <media:thumbnail url="http://i.ytimg.com/vi/yk6wkfVNFQE/default.jpg" height="90" width="120" time="00:02:07" yt:name="default" />          
        <yt:videoid>yk6wkfVNFQE</yt:videoid>
    </media:group>

</entry>

I need the "videoid" and the "url" from thumbnail-default

Thank you!


回答1:


Similar to the getElementsByTagName() that you're already using, to access namespaced elements (recognisable by namespace:element-name) you can use the getElementsByTagNameNS() method.

The documenation (linked above) should give you the technical lowdown on how to use it, suffice to say it will be similar to the following (also using getAttribute()).

$yt    = 'http://gdata.youtube.com/schemas/2007';
$media = 'http://search.yahoo.com/mrss/';

// Inside your loop
$id    = $video->getElementsByTagNameNS($yt, 'videoid')->item(0)->nodeValue;
$thumb = $video->getElementsByTagNameNS($media, 'thumbnail')->item(0)->getAttribute('url');

Hopefully that should give you a spring-board to leap into accessing namespaced items within your XML documents.



来源:https://stackoverflow.com/questions/4902288/help-parsing-xml-with-domdocument

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