从 Google RSS 提要 xml 中获取前 9 个元素 PHP
Get first 9 elements from Google RSS feed xml in PHP
我目前正在使用 Google RSS 提要。我收到了这个 XML 回复。
<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>©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>
我正在使用这个 foreach()
遍历所有项目:
$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/>";
}
但是这个 foreach returns 我所有的项目。
我怎样才能从这个 XML 中只获得前 9 项?
轻松快速修复:-
$i = 0;
foreach ($rss->channel->item as $item) {
if($i<9){
echo $item->title."<br/>";
echo $item->link."<br/>";
echo $item->pubDate."<br/>";
}
$i++;
}
更好的解法是:-
$array = array_slice($rss->channel->item,0,9);
foreach ($array as $item) {
echo $item->title."<br/>";
echo $item->link."<br/>";
echo $item->pubDate."<br/>";
}
好吧,我找到了答案:
$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;
}
我目前正在使用 Google RSS 提要。我收到了这个 XML 回复。
<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>©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>
我正在使用这个 foreach()
遍历所有项目:
$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/>";
}
但是这个 foreach returns 我所有的项目。
我怎样才能从这个 XML 中只获得前 9 项?
轻松快速修复:-
$i = 0;
foreach ($rss->channel->item as $item) {
if($i<9){
echo $item->title."<br/>";
echo $item->link."<br/>";
echo $item->pubDate."<br/>";
}
$i++;
}
更好的解法是:-
$array = array_slice($rss->channel->item,0,9);
foreach ($array as $item) {
echo $item->title."<br/>";
echo $item->link."<br/>";
echo $item->pubDate."<br/>";
}
好吧,我找到了答案:
$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;
}