tags:

views:

33

answers:

2

Here is my code:

<?php

$RSSFEEDS = array(
    0 => "http://samnabi.posterous.com/rss.xml",
);
function FormatRow($date, $title, $link, $description) {
return <<<HTML
<p class="blogdate">$date</p><h2 class="blogtitle">$title</h2>
<div class="clearer">&nbsp;</div>
$description
HTML;
}
ob_start();
if (!isset($feedid)) $feedid = 0;
$rss_url = $RSSFEEDS[$feedid];
$rss_feed = file_get_contents($rss_url);
$rss_feed = str_replace("<![CDATA[", "", $rss_feed);
$rss_feed = str_replace("]]>", "", $rss_feed);
$rss_feed = str_replace("\n", "", $rss_feed);
$rss_feed = preg_replace('#<image>(.*?)</image>#', '', $rss_feed, 1 );
preg_match_all('#<pubDate>(.*?)</pubDate>#', $rss_feed, $date, PREG_SET_ORDER); 
preg_match_all('#<title>(.*?)</title>#', $rss_feed, $title, PREG_SET_ORDER);  
preg_match_all('#<link>(.*?)</link>#', $rss_feed, $link, PREG_SET_ORDER);
preg_match_all('#<description>(.*?)</description>#', $rss_feed, $description, PREG_SET_ORDER);
if(count($title) <= 1) {
    echo "No new blog posts. Check back soon!";
}
else {
    for ($counter = 1; $counter <= 3; $counter++ ) {
        if(!empty($title[$counter][1])) {
            $title[$counter][1] = str_replace("&", "&", $title[$counter][1]);
            $title[$counter][1] = str_replace("&apos;", "'", $title[$counter][1]);          
            $row = FormatRow($date[$counter][1],$title[$counter][1],$link[$counter][1],$description[$counter][1]);
            echo $row;
        }
    }
} 
ob_end_flush();

?> 

When this script is run, the first item displays the second item's pubDate. The second item displays the third item's pubDate, and so on. So the dates that are shown are not the dates that you see in the original XML file. How do I fix this?

Bonus question: how do I strip characters off the beginning and end of the pubDate tag, so that I end up with "15 May 2010" instead of "Sat, 15 May 2010 03:28:00 -0700" ?

+1  A: 

I've said it before, so I'll say it again: Use Magpie RSS to parse your RSS feeds. It takes care of all this stuff for you, and will be much more reliable.

Chris Arguin
Super duper. Thanks a lot!
Sam Nabi
A: 

Magpie RSS works great. Here's the code I used to replace what was in my original question:

<?php

define('MAGPIE_INPUT_ENCODING', 'UTF-8');
define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');

//Tell it to use the fetch script to grab the RSS feed
require_once('magpie/rss_fetch.inc');

//Now it knows how to fetch RSS, tell it which one to fetch
$rss = fetch_rss('http://samnabi.posterous.com/rss.xml');

//In this case, we only want to display the first 3 items
$items = array_slice($rss->items,0,3);

//Now we tell Magpie how to format our output
foreach ($items as $item) {
    $title = $item['title'];
    $date = date('d M Y', strtotime($item['pubdate']));
    $link = $item['link'];
    $description = $item['description'];       

    //And now we want to put it all together.
    echo "<p>$date</p><h2>$title</h2><p>$description</p>";
}

?>
Sam Nabi