我已经调整了此处http://www.w3schools.com/php/php_ajax_rss_reader.asp中的代码,将XML转换为HTML,并且工作正常。
但我所坚持的是,当Feed可以包含不同数量的项目时,它会显示所有 Feed中的项目。 Feed每天发布,其中可以包含12到20篇文章,我想展示所有这些文章。
在For循环中for ($i=0; $i<=12; $i++)
如果我将条件设置为大于文章数,我会收到错误PHP Fatal error: Call to a member function getElementsByTagName()
,因此我无法将其设置为大数字。
如果我删除条件,我会得到同样的错误。
我也无法弄清楚如何计算物品的数量;如果我能做到这一点,解决方案将很容易。
Feed是在内部创建的,因此我可以让我的同事在Feed中插入项目数量;这是最好的方式吗?
谢谢!
答案 0 :(得分:0)
如果您不知道Feed中的项目数,则可以使用foreach
循环完成所有项目。以下是使用RSS feed from the PHP tag on StackOverflow的示例。看一下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";
}
使用foreach
循环意味着您不必花时间计算阵列中有多少项目,而且不必使用for ($i = 0; $i < 500; $i++)
设置数组迭代器