0

这里有我的代码:

<?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...

我该怎么做才能只显示第一条新闻?

4

3 回答 3

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++;
        }
    }
    ?>
于 2012-12-09T17:40:59.090 回答
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>");
}?>
于 2012-12-09T17:41:52.037 回答
-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>");

}
于 2012-12-09T17:39:04.640 回答