2012-02-23 56 views
0

使用DomDocument獲取RSS提要,但遇到了奇怪的問題。如果我抓住一些像http://rss.slashdot.org/Slashdot/slashdot這樣的RSS feed,它可以正常工作。然而,我試圖解析的RSS源給我的問題:http://www.ryanhache.com/feedDOMDocument :: getElementsByTagName PHP中沒有抓取頻道

它似乎無法找到通道標記,然後通過該循環。我繼承的函數如下所示,並用RSS_Retrieve($ url)調用。我在這些功能中錯過了什麼,或者我正在拉動的Feed有什麼問題?

function RSS_Tags($item, $type) 
{ 
    $y = array(); 
    $tnl = $item->getElementsByTagName("title"); 
    $tnl = $tnl->item(0); 
    $title = $tnl->firstChild->textContent; 

    $tnl = $item->getElementsByTagName("link"); 
    $tnl = $tnl->item(0); 
    $link = $tnl->firstChild->textContent; 

    $tnl = $item->getElementsByTagName("pubDate"); 
    $tnl = $tnl->item(0); 
    $date = $tnl->firstChild->textContent; 

    $tnl = $item->getElementsByTagName("description"); 
    $tnl = $tnl->item(0); 
    $description = $tnl->firstChild->textContent; 

    $y["title"] = $title; 
    $y["link"] = $link; 
    $y["date"] = $date; 
    $y["description"] = $description; 
    $y["type"] = $type; 

    return $y; 
} 

function RSS_Channel($channel) 
{ 
    global $RSS_Content; 

    $items = $channel->getElementsByTagName("item"); 

    // Processing channel 

    $y = RSS_Tags($channel, 0);  // get description of channel, type 0 
    array_push($RSS_Content, $y); 

    // Processing articles 

    foreach($items as $item) 
    { 
     $y = RSS_Tags($item, 1); // get description of article, type 1 
     array_push($RSS_Content, $y); 
    } 
} 

function RSS_Retrieve($url) 
{ 
    global $RSS_Content; 

    $doc = new DOMDocument(); 
    $doc->load($url); 

    $channels = $doc->getElementsByTagName("channel"); 

    $RSS_Content = array(); 

    foreach($channels as $channel) 
    { 
     RSS_Channel($channel); 
    } 

} 
+0

您的'http:// www.ryanhace.com/feed'網址似乎是404? – 2012-02-23 22:14:47

+0

Bah拼錯了URL:http://www.ryanhache.com/feed – Jeff 2012-02-23 22:17:10

+0

似乎沒問題。你的實際產出和預期產出是多少? – 2012-02-23 22:43:06

回答

1

您的代碼似乎工作,但任務可以簡單和不使用全局變量來完成更多。

function RSS_Tags($node, $map, $type) { 
    $item = array(); 
    foreach ($map as $elem=>$key) { 
     $item[$key] = (string) $node->{$elem}; 
    } 
    $item['type'] = $type; 
    return $item; 
} 

function RSS_Retrieve($url) { 
    $rss = simplexml_load_file($url); 
    $elements = array('title'=>'title', 'link'=>'link', 
     'pubDate'=>'date', 'description'=>'description'); 
    $feed = array(); 
    foreach ($rss->channel as $channel) { 
     $feed[] = RSS_Tags($channel, $elements, 0); 
     foreach ($channel->item as $item) { 
      $feed[] = RSS_Tags($item, $elements, 1); 
     } 
    } 
    return $feed; 
} 

$url = 'http://www.ryanhache.com/feed'; 
$RSS_Content = RSS_Retrieve($url);