Question

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

No correct solution

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top