How to get the first 5 records of xml?

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>
                            ";
                        }
                    ?>
    
asked by anonymous 22.02.2017 / 20:43

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>
        ";
    }
?>
    
22.02.2017 / 21:33