2012-05-16 191 views
2

將RSS feed加載到PHP feed中的最佳方式是什麼?將rss feed加載到php

我也想處理media:content問題來顯示圖像。 在這一刻我有以下代碼,但我不知道這是否是最好的。

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

    } 
?> 

回答

8

檢查:

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

?> 
+0

好的謝謝你,請你舉個例子來打印一些文字,因爲在我的例子中我使用了dom元素。 – Niels

+0

查看代碼更新 – ioseb

+1

@ioseb:有點提示:帶有'%s'的printf將使PHP將simplexml元素轉換爲字符串,所以如果您使用printf,則不需要'(string)'類型轉換;) – hakre

0

可以嘗試這樣:

<?php 

$feed = simplexml_load_file('http://www.hln.be/rss.xml'); 

print_r($feed); 

?> 

這給你對象,它可以代替直接使用與所述數據的頂部附加層通信的/陣列結構(即DOM)。

+0

當我使用的代碼,我得到的唯一的事情就是文字。但我仍然無法訪問圖像 – Niels

+0

您需要單獨獲取圖像。圖像(以及其他媒體信息)不會嵌入到RSS文檔中。 RSS規範只提供外部資源的鏈接,這些外部資源需要像HTML一樣在瀏覽器中提取。 – ioseb

+0

據我所知,他們提供了這樣的鏈接 但如何我是否得到槽這個。我瞭解img src =變量 – Niels