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 フィードの最初のニュースだけを表示したいのです。

数えてみると、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 に答える