loading rss feed into php

php, rss

Solution

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>';
}

?>

Problem

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 . '"/>'; } ?> ```

Original source