如何使用 simpleXML 和position() 循环和显示(n) 个提要

发布于 2024-08-19 07:16:12 字数 616 浏览 5 评论 0原文

我正在使用 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 数据与

http://deniselashlley.co.uk/test/data.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

http://deniselashlley.co.uk/test/data.xml

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

生死何惧 2024-08-26 07:16:12

这感觉像是重新发布,但无论如何...

NiseNise 想要对节点进行排序,然后保留前 5 个节点。问题是这个 XPath 表达式选择文档中的前 5 个节点,然后该方法对它们进行排序。您需要做的是对所有节点进行排序,然后只处理前 5 个节点。

foreach($xml->sortedXPath('TV[ProgrammeName="MTV"]', 'TransmissionDate', SORT_DESC) as $i => $item)
{
    if ($i > 5)
    {
        break;
    }

    print "<a href='?v=".$item->ID."&a=false' class='link'>\n";
    // etc...
}

我忘了提及,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.

foreach($xml->sortedXPath('TV[ProgrammeName="MTV"]', 'TransmissionDate', SORT_DESC) as $i => $item)
{
    if ($i > 5)
    {
        break;
    }

    print "<a href='?v=".$item->ID."&a=false' class='link'>\n";
    // etc...
}

I forgot to mention, sortedXPath() isn't part of SimpleXML, it's part of a library extending SimpleXML, hence the retagging.

李不 2024-08-26 07:16:12

您是否考虑过循环将从 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文