Search code examples
phpxmlforeachrssgoogle-feed-api

Get first 9 elements from Google RSS feed xml in PHP


I'm currently working with Google RSS feeds. I received this XML response.

<rss version="2.0">
<channel>
<generator>NFE/1.0</generator>
<title>blockchain - Google News</title>
<link>...</link>
<language>en</language>
<webMaster>news-feedback@google.com</webMaster>
<copyright>&copy;2017 Google</copyright>
<pubDate>Fri, 17 Nov 2017 09:41:26 GMT</pubDate>
<lastBuildDate>Fri, 17 Nov 2017 09:41:26 GMT</lastBuildDate>
<image>...</image>
<description>Google News</description>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
</channel>
</rss>

I'm using this foreach() to loop through all items:

$rss = simplexml_load_file('https://news.google.com/news/rss/headlines/section/q/blockchain/blockchain?ned=us&hl=en&gl=US');

foreach ($rss->channel->item as $item) {
    echo $item->title."<br/>";
    echo $item->link."<br/>";
    echo $item->pubDate."<br/>";
}

But this foreach returns me all items.

How can I get only first 9 items from this XML?


Solution

  • Easy and quick fix:-

    $i = 0;
    foreach ($rss->channel->item as $item) {
      if($i<9){
        echo $item->title."<br/>";
        echo $item->link."<br/>";
        echo $item->pubDate."<br/>";
      }
     $i++;
    }
    

    Better solution is:-

    $array = array_slice($rss->channel->item,0,9);
    
    foreach ($array as $item) {
      echo $item->title."<br/>";
      echo $item->link."<br/>";
      echo $item->pubDate."<br/>";
    }
    

    Reference:- PHP manual: array_slice