Reading blog feed using PHP

Well, once I made the last post about how to read a blog feed in ASP.Net using LINQ I just wondered if I would be able to do it in PHP too, so I did it.

Here’s the code:

function getBlogFeed($urlRSS) {
  $doc = new DOMDocument();
  $doc->load($urlRSS);
  $arrFeeds = array();
  foreach ($doc->getElementsByTagName('item') as $node):
    $itemRSS = 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
      );
    array_push($arrFeeds, $itemRSS);
  endforeach;
  
  return $arrFeeds;
}

Once you have that done you can just show it as you wish, this is my show function but have in mind it uses my css styles (you can have a look at how it looks at my home page).

function showBlogFeed($urlRSS){
  if ($urlRSS !== ''):
    $arrFeeds = getBlogFeed($urlRSS);

      if($arrFeeds):
        echo '<div id="feed">';
          foreach ($arrFeeds as $node) {
            echo '<div class="post">';
                echo '<div class="titulo"><a href="' . $node["link"] . '">' . $node["title"] . '</a></div>';
                echo '<p class="fecha">' . date('j M Y', $node["date"]) . '</p><br />';
			    echo '<div class="contenido">' . $node["desc"] . '</div>';
                echo '<p class="more"><a href="' . $node["link"] . '">m&aacute;s</a></p>';
		    echo '</div>';
          }
        echo '</div>';
      endif;
  endif;
}
}

Leave a Reply

Close Bitnami banner
Bitnami