如何使用 simpleXML 和position() 循环和显示(n) 个提要
我正在使用 simpleXML,并且我想使用position() 方法循环遍历提要以仅显示 5 个显示,但对于让它工作并没有任何乐趣
foreach($xml->sortedXPath('TV[position() < 5 and ProgrammeName="MTV"]', 'TransmissionDate', SORT_DESC) as $i => $item)
{
print "<a href='?v=".$item->ID."&a=false' class='link'>\n";
print "\t<span class=\"text\">" .trunc($item->ShortSynopsis,25, " "). "</span>\n";
print "\t</a>";
}
关于如何使其工作的任何建议
这是我正在工作的 XML 数据与
I am using simpleXML and I want to loop though the feed to only display 5 shows using the position() method, but have no joy in getting it to work
foreach($xml->sortedXPath('TV[position() < 5 and ProgrammeName="MTV"]', 'TransmissionDate', SORT_DESC) as $i => $item)
{
print "<a href='?v=".$item->ID."&a=false' class='link'>\n";
print "\t<span class=\"text\">" .trunc($item->ShortSynopsis,25, " "). "</span>\n";
print "\t</a>";
}
any suggestions on how I can get this working
this is the XML data I am working with
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这感觉像是重新发布,但无论如何...
NiseNise 想要对节点进行排序,然后保留前 5 个节点。问题是这个 XPath 表达式选择文档中的前 5 个节点,然后该方法对它们进行排序。您需要做的是对所有节点进行排序,然后只处理前 5 个节点。
我忘了提及,
sortedXPath()
不是 SimpleXML 的一部分,它是扩展 SimpleXML 的库,因此需要重新标记。This feels like a repost, but anyway...
NiseNise wants to sort nodes then keep the top 5. The problem is that this XPath expression selects the first 5 nodes in the document, then the method sorts them. What you need to do is sort all the nodes then only process the first 5.
I forgot to mention,
sortedXPath()
isn't part of SimpleXML, it's part of a library extending SimpleXML, hence the retagging.您是否考虑过循环将从
item[0]
开始?所以$i > 5
将输出前 6 个节点,因为计数将从第 0 项开始。只需将其更改为$i > 4
这应该可以解决你的问题。Have you considered that your loop will begin at
item[0]
? So$i > 5
will output the first 6 nodes because the count would begin at item 0. Simply change it to$i > 4
and that should fix your problem.