从 WordPress RSS feed 中获取节点属性缩略图

问题描述 投票:0回答:1

我一直在努力让这段看似简单的代码发挥作用。 我正在从 WordPress 网站加载 RSS,除了缩略图之外,一切都工作正常。由于在 XML 中它们被设置为属性而不是 nodeValue,所以我似乎无法导入它们。

$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);
}
php wordpress rss getattribute
1个回答
0
投票

几个小时后,我创建了另一段可以工作的代码。如果有人需要的话,这里是:

$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);


}
© www.soinside.com 2019 - 2024. All rights reserved.