views:

162

answers:

2

Hi,

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

A: 

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.

Josh Davis
Yeah I had that before but then certain times during the week it would display 6 shows (as a new show is added), so I was hoping the position() method would work better.
NiseNise
That would be *extremely* weird. I can't think of a situation where this loop would output more than 5 entries. If anything, initialize `$i` yourself and increment it yourself inside of the loop. It will be *impossible* then to output more than 5, unless of course you have another routine that resets the value of `$i`. Most likely, your bug is elsewhere.
Josh Davis
I do have this additional filter that does not to display future shows before they are actually transmitted$today_date = date('D j M, g:ia');if(strtotime($item->TransmissionDate) < time(strtotime($today_date))){ print "<a href='?v=".$item->ID."}maybe this might affect it????
NiseNise
A: 

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.

Imminent