Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help parsing XML with DOMDocument

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!

like image 909
Titan Avatar asked Feb 04 '11 19:02

Titan


1 Answers

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.

like image 104
salathe Avatar answered Sep 22 '22 11:09

salathe