Php RSS到HTML,包含不同数量的元素

Php RSS到HTML,包含不同数量的元素,php,rss,Php,Rss,我已经修改了这里的代码,将XML转换成HTML,效果很好 但是我坚持的是让它显示提要中的所有项目,而提要可以有不同数量的项目。该提要每天发布,可以包含12-20篇文章,我想展示所有这些文章 在For循环For($i=0;$i如果您不知道提要中的项目数,可以使用foreach循环遍历所有项目。下面是使用的示例。查看rss格式,以便查看每个项目的外观,并将其与下面的代码进行比较 # start off like the w3schools code... $xml=("https://stackov

我已经修改了这里的代码,将XML转换成HTML,效果很好

但是我坚持的是让它显示提要中的所有项目,而提要可以有不同数量的项目。该提要每天发布,可以包含12-20篇文章,我想展示所有这些文章


在For循环
For($i=0;$i如果您不知道提要中的项目数,可以使用
foreach
循环遍历所有项目。下面是使用的示例。查看rss格式,以便查看每个项目的外观,并将其与下面的代码进行比较

# start off like the w3schools code...
$xml=("https://stackoverflow.com/feeds/tag?tagnames=php&sort=newest");

$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

# StackOverflow uses the <entry> element for each separate item.
# find all the "entry" items. This returns an array of matching entry elements
$items = $xmlDoc->getElementsByTagName('entry');

# go through the array of "entry" elements one at a time
# $items is the array of <entry> elements
# $i is set to each <entry> in turn, starting from the first one on the page
foreach ($items as $i) {

    # some sample code to get the title, tags, and link
    $title = $i->getElementsByTagName('title')->item(0)->nodeValue;
    $href = $i->getElementsByTagName('link')->item(0)->getAttribute('href');
    $tags = $i->getElementsByTagName('category');
    $tag_arr = [];
    foreach ($tags as $t) {
        $tag_arr[] = $t->getAttribute('term');
    }
    echo "Title: $item_title; tags: " . implode(", ", $tag_arr) . ";\nhref: $href\n\n";
}
#从代码开始。。。
$xml=(”https://stackoverflow.com/feeds/tag?tagnames=php&sort=newest");
$xmlDoc=新的DOMDocument();
$xmlDoc->load($xml);
#StackOverflow为每个单独的项目使用元素。
#查找所有“条目”项。这将返回匹配条目元素的数组
$items=$xmlDoc->getElementsByTagName('entry');
#逐个遍历“entry”元素数组
#$items是元素数组
#$i从页面上的第一个开始依次设置为每个
foreach(项目为$i){
#获取标题、标记和链接的一些示例代码
$title=$i->getElementsByTagName('title')->item(0)->nodeValue;
$href=$i->getElementsByTagName('link')->item(0)->getAttribute('href');
$tags=$i->getElementsByTagName('category');
$tag_arr=[];
foreach($t标记){
$tag_arr[]=$t->getAttribute('term');
}
echo“Title:$item_Title;tags:”.intlode(“,”,$tag_arr)。“;\nhref:$href\n\n”;
}

使用
foreach
循环意味着您不必计算数组中有多少项,也不必使用
for($i=0;$i<500;$i++)设置数组迭代器

谢谢!我也在r/php上问过这个问题,那里的人也提到将其改为foreach。但另一个人说有一个“length”元素非常适合这个,它非常有效!对于($I=0;$I<$xmlDoc->getElementsByTagName('item')->length;$I++),我通常不使用($I=0;$I)的