简体   繁体   中英

Display media file from Wordpress RSS feed

I am using the below code to grab data from a wordpress RSS feed. However I am having an issue with grabing the 'media file' from the feed.

<?php
        $rss = new DOMDocument();
        $rss->load('http://www.ipa.co.uk/rss/jobs');
        $feed = array();
        foreach ($rss->getElementsByTagName('item') as $node) {
            $item = array ( 
                'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
                'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
                'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
                'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
                'image' => $node->getElementsByTagName('enclosure')->item(0)->getAttribute('url'),
                );
            array_push($feed, $item);
        }
        $limit = 20;
        for($x=0;$x<$limit;$x++) {
            $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
            $link = $feed[$x]['link'];
            $description = $feed[$x]['desc'];
            $date = date('l F d, Y', strtotime($feed[$x]['date']));?>
            <div class="col-md-4 job-item">
                <div class="job-item__inner">
                    <?php
                    echo '<h2 class="job-title"><a href="'.$link.'" title="'.$title.'">'.$title.'</a></h2>';
                    echo '<small><em>Posted on '.$date.'</em></small></p>';
                    echo '<p>'.$description.'</p>';
                    echo '<img src="'.$image.'"/>';?>
                </div>
            </div>
        <?php } ?>

I have seen this answer on SO which helped me add in the getElementsByTagName('enclosure')->item(0)->getAttribute('url') . However its not displaying any img src. I think 'enclosure' is correct as I get errors if I change it to something like this getElementsByTagName('media')->item(0)->getAttribute('url')

The issue must be that I'm targeting the wrong area of the feed. But I'm not sure what to add to get the image displaying.

You should definitely enable NOTICES while developing with PHP. This would have led you to the answer: Your extraction code is correct but in the for-loop you need an additional line

$image = $feed[$x]['image'];

otherwise the variable $image is undefined n this context.


//edit: By the way the 2 loops are inefficient. Better use only the foreach loop and a counter. Once the counter is at 20, do a break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM