简体   繁体   中英

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?

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

Well I found the answer:

   $i = 0;

   foreach ($rss->channel->item as $item) {
      $i++;

      echo $item->title."<br/>";
      echo $item->link."<br/>";
      echo $item->pubDate."<br/>";


      if($i == 10) break;
   } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM