How to get the first 5 xml records?

Asked

Viewed 72 times

0

<?php
                        $xml = simplexml_load_file('http://g1.globo.com/dynamo/economia/rss2.xml') or die("erro carregar arquivo");

                        foreach ($xml->channel->item as $noticia) {
                            $noticia->pubDate = date('d/m/Y');

                            echo "
                                <li>
                                    <div class=\"timeline-badge\"><i class=\"fa fa-check\"></i>
                                    </div>
                                    <div class=\"timeline-panel\">
                                        <div class=\"timeline-heading\">
                                            <p><small class=\"text-muted\"><i class=\"fa fa-clock-o\"></i> $noticia->pubDate</small>
                                            </p>
                                        </div>

                                        <div class=\"timeline-body\">
                                          <a href=\"$noticia->link\" target=\"_blank\">$noticia->title</a><br>
                                        </div>
                                    </div>
                                </li>
                            ";
                        }
                    ?>
  • Put a counter on that foreach,.

  • Rodrigo Sartori, I think it was worth it!

1 answer

0

<?php
    $limite = 5;
    $xml = simplexml_load_file('http://g1.globo.com/dynamo/economia/rss2.xml') or die("erro carregar arquivo");
    $noticias = $xml->xpath(sprintf('/rss/channel/item[position() <= %d]', $limite));

    foreach ($noticias as $noticia) {
        $noticia->pubDate = date('d/m/Y');

        echo "
            <li>
                <div class=\"timeline-badge\"><i class=\"fa fa-check\"></i>
                </div>
                <div class=\"timeline-panel\">
                    <div class=\"timeline-heading\">
                        <p><small class=\"text-muted\"><i class=\"fa fa-clock-o\"></i> $noticia->pubDate</small>
                        </p>
                    </div>

                    <div class=\"timeline-body\">
                        <a href=\"$noticia->link\" target=\"_blank\">$noticia->title</a><br>
                    </div>
                </div>
            </li>
        ";
    }
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.