Display media files from a wordpress rss feed

2019-09-15 17:03发布

问题:

I am parsing the rss feed of a regular wordpress.com blog using PHP in order to display a preview of the posts on my website.

It correctly displays: Title, Description and publication date. BUT I would like to display also the images of each post. If I open the feed's URL, there is a chart with "media files links", but I don't know how to access those links.

Do you have any suggestions?

This is the code I am using:

<?php

            $xml=("http://testmustard.wordpress.com/feed/");

            $xmlDoc = new DOMDocument();

            $xmlDoc->load($xml);

            $items=$xmlDoc->getElementsByTagName('item');
            $max_items= 15;

        ?>      

        <?php foreach( $items as $i => $item ):?>


        <?php
            if($i>=$max_items) break;

            $title = $item->getElementsByTagName( "title" )->item(0)->nodeValue; 
            $description = $item->getElementsByTagName( "description" )->item(0)->nodeValue; 
            $data = $item->getElementsByTagName( "pubDate" )->item(0)->nodeValue;
        ?>
            <div class="posts">
                <div class="rssentry">
                    <h2><?php echo $title?></h2>
                    <div class="rsscontent"><?php echo html_entity_decode($description)?></div>
                    <div class="metadata"><?php echo $data?></div>
                </div>              
            </div>
        <?php endforeach;?>
        </div>  

Thanks a lot for your help

回答1:

PHP

<?php

$maxItems = 15;

$Document = new DOMDocument();
$Document->load('http://testmustard.wordpress.com/feed/');

$NodeList = $Document->getElementsByTagName('item');

$i = 0;
foreach ($NodeList as $Node) {
    if ($i++ >= $maxItems) {
        break;
    }

    $media = $Node->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'content');
    if ($media->length > 0) {
        $imageUrl = $media->item(0)->getAttribute('url');
        echo "$imageUrl\n";
    } else {
        echo "No media:content\n";
    }
}

The key is getElementsByTagNameNS. It let's you use the media namespace so you can snag the content.