2010-07-04 49 views
0

這裏是我的代碼:當解析RSS提要,則顯示錯誤的日期

<?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(); 

?> 

當這個腳本運行後,第一項顯示第二項的pubdate的。第二個項目顯示第三個項目的pubDate,依此類推。所以顯示的日期不是您在原始XML文件中看到的日期。我該如何解決?

獎勵問題:我如何去掉pubDate標籤的開頭和結尾的字符,以便我以「2010年5月15日」而非「星期六,2010年5月15日03:28:00 -0700」結束「?

回答

1

我說過它before,所以我會再說一遍:使用Magpie RSS解析您的RSS提要。它爲你處理所有這些東西,並且會更加可靠。

+0

超級騙子。非常感謝! – 2010-07-04 03:54:47

0

鵲RSS的偉大作品。這裏是我用來取代我原來的問題的代碼:

<?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>"; 
} 

?>