如果在ForEach里面

时间:2012-12-09 17:36:06

标签: php

这里有我的代码:

<?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并解析它以便不显示图像。直到这里好。 但是现在,我只希望从RSS Feed中看到第一条新闻,而不是所有新闻。

如果我计算一下,它会告诉我有25条新闻。

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

如何只显示第一条新闻?

3 个答案:

答案 0 :(得分: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++;
        }
    }
    ?>

答案 1 :(得分: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>");
}?>

答案 2 :(得分:-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>");

}