2012-12-09 56 views
-1

這裏有我的代碼:如果裏面的ForEach

<?php 
$url = "http://feeds.hipertextual.com/alt1040"; 
$rss = simplexml_load_file($url); 
if($rss) { 
$items = $rss->channel->item; 

    foreach($items as $item) { 
     $title = $item -> title; 
     $link = $item -> link; 
     $description = $item -> description; 
     $replace = preg_replace("/<img[^>]+\>/i", "", $description); 
     echo utf8_decode("<h3><a href=$link>$title</a></h3>"); 
     echo utf8_decode("<p>$replace</p>"); 

    } 
} 
?> 

我從那個URL的RSS和我解析它,使圖像不會出現。直到這裏OK。 但現在,我只想顯示RSS Feed的第一條新聞,而不是所有的新聞。

如果我做了一個計數,它告訴有25個新聞項目。

$count = count ($items); 
echo $count; //25 news... 

我該怎麼做只顯示第一條新聞?

回答

0

在此示例中,您可以插入任何數字而不是1個項目。

<?php 
    $url = "http://feeds.hipertextual.com/alt1040"; 
    $rss = simplexml_load_file($url); 
    if($rss) { 
    $items = $rss->channel->item; 
    $count =0; 
     foreach($items as $item) { 
      if ($count<1) { 
      $title = $item -> title; 
      $link = $item -> link; 
      $description = $item -> description; 
      $replace = preg_replace("/<img[^>]+\>/i", "", $description); 
      echo utf8_decode("<h3><a href=$link>$title</a></h3>"); 
      echo utf8_decode("<p>$replace</p>"); 
      } 
      $count++; 
     } 
    } 
    ?> 
+0

OP只搜索1項。 –

+0

misunderstanded,編輯答案。 –

+0

對我來說,最好的答案是,我可以選擇我想要展示的新聞。非常感謝你! – seRgiOOOOOO

-1

爲什麼不試着不回聲描述部分?

$url = "http://feeds.hipertextual.com/alt1040"; 
$rss = simplexml_load_file($url); 
if($rss) { 
$items = $rss->channel->item; 
$isNewsPage = true; // set here to false if you are on main page 

foreach($items as $item) { 
    $title = $item -> title; 
    $link = $item -> link; 
    $description = $item -> description; 
    $replace = preg_replace("/<img[^>]+\>/i", "", $description); 
    echo utf8_decode("<h3><a href=$link>$title</a></h3>"); 

    if($isNewsPage) 
     echo utf8_decode("<p>$replace</p>"); 

} 
+0

因爲我想要說明部分。但只有我的主要網站上的第一條新聞,在新聞部分,我會顯示所有新聞 – seRgiOOOOOO

+0

你可以easliy把一條if語句放到一個foreach中......在上面的例子中,你只需要告訴你的foreach是否它是一個新聞頁面或有變量或任何其他條件的主頁 – Mik

0

如果你只希望顯示的第一個項目,則只需設置$item變量的第一個項目陣列。那麼你可以跳過整個foreach:

<?php 
$url = "http://feeds.hipertextual.com/alt1040"; 
$rss = simplexml_load_file($url); 
if($rss) { 
    $item = $rss->channel->item[0]; 
    $title = $item -> title; 
    $link = $item -> link; 
    $description = $item -> description; 
    $replace = preg_replace("/<img[^>]+\>/i", "", $description); 
    echo utf8_decode("<h3><a href=$link>$title</a></h3>"); 
    echo utf8_decode("<p>$replace</p>"); 
}?> 
+0

非常感謝! – seRgiOOOOOO