user2779376
user2779376

Reputation: 21

Getting attribute thumbnail from node from a WordPress RSS feed

I've been trying to get this seemingly easy piece of code to work. I'm loading RSS from a WordPress site and it all works fine except for the thumbnails. Since in the XML they are set as an attribute instead of a nodeValue, I can't seem to import them.

$rss = new DOMDocument();
$rss->load('http://goalprogramme.wordpress.com/feed/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
    // in XML it looks like <media:thumbnail url="http://goalprogramme.files.wordpress.com/2014/01/dsc_0227.jpg?w=150"/>
    
    //echo $node->getElementsByTagName('media:thumbnail')->item(0)->getAttribute('url');
    
    //push items
    $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,
        'thumbnail' => $node->getElementsByTagName('media:thumbnail')->item(0)->getAttribute('url') // this line doesn't work !!!                
    );
    array_push($feed, $item);
}

Upvotes: 1

Views: 563

Answers (1)

user2779376
user2779376

Reputation: 21

Hours later i've created another piece of code that does work. If anyone needs it it, here it is:

$feed_array = array();
$feed = simplexml_load_file('http://goalprogramme.wordpress.com/feed/');

foreach ($feed->channel->item as $item) {
  $title       = (string) $item->title;
  $description = (string) $item->description;
  $link = (string) $item->link;
  $date = (string) $item->date;

  if ($media = $item->children('media', TRUE)) {
    if ($media->thumbnail) {
      $attributes = $media->thumbnail->attributes();
      $thumbnail     = (string)$attributes['url'];
    }
  }

  $item = array ( 
            'title' => $title ,
            'desc' => $description,
            'link' => $link,
            'date' => $date,
            'thumbnail' => $thumbnail                
            );
  array_push($feed_array, $item);


}

Upvotes: 0

Related Questions