loading rss feed into php

心不动则不痛 提交于 2019-12-08 03:05:40

问题


What's the best way to load an RSS feed into a PHP feed?

I also want to handle the media:content problems to display a image. At this moment I have the following code but I don't know if this is the best.

<?php
    $rss = new DOMDocument();
    $rss->load('http://www.hln.be/rss.xml');
    $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,
            'media' => $node->getElementsByTagName('media:content url')->item(0)->nodeValue,

            );
        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']));
        $image = $feed[$x]['media'];

        echo '<p><strong><a href="'.$link.'" title="'.$title.'">'.$title.'</a></strong><br />';
        echo '<small><em>Posted on '.$date.'</em></small></p>';
        echo '<p>'.$description.'</p>';
        echo '<img src="' . $image . '"/>';

    }
?>

回答1:


Check this:

<?php

$feed = simplexml_load_file('http://www.hln.be/rss.xml');

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

  print '<div>';

  printf(
    '<h2>%s</h2><p>%s</p>', 
    $title, 
    $description
  );

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

      printf('<div><img src="%s" alt="" /></div>', $imgsrc);
    }
  }

  echo '</div>';
}

?>



回答2:


You can try this:

<?php

$feed = simplexml_load_file('http://www.hln.be/rss.xml');

print_r($feed);

?>

This gives you object/array structure which you can use directly instead of communicating with additional layer(i.e. DOM) on top of the data.



来源:https://stackoverflow.com/questions/10617142/loading-rss-feed-into-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!