开发者

How to loop and display (n) feeds using simpleXML and position()

开发者 https://www.devze.com 2022-12-18 01:22 出处:网络
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

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 开发者_如何学Python=> $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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号