Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

php - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...