SimpleXML read specific number of childs only
I'm using SimpleXML to read an XML file containing news and events for my website. I'm using foreach to loop through my pre-defined xml tags. However, on my website, I need to feature only three news and events which is the childs of the root of my xml.
<list>
<newsevent>
<date>AUG 7</date>开发者_高级运维
<description>news</description>
</newsevent>
<newsevent>
<date>AUG 6</date>
<description>news/description>
</newsevent>
<newsevent>
<date>AUG 5</date>
<description>news</description>
</newsevent>
</list>
I'm using foreach loop from my php file
foreach($xml->newsevent as $newsevent)
{
echo "$newsevent->date";
echo "$newsevent->description";
}
The XML file will be treated as database for news and events, and obviously there would be lots of record. How could I only show a specific number of newsevents?
You could just add some counter variable, keeping track of the number of times you've looped, and exiting the loop when you've looped enough times :
$counter = 0;
foreach($xml->newsevent as $newsevent)
{
echo "$newsevent->date";
echo "$newsevent->description";
$counter++;
if ($counter >= 3) {
break;
}
}
Still, note that with SimpleXML
(same with DOMDocument
, BTW), the entire XML document will be parsed and loaded into memory, no matter how many items you need to read from it.
If your document is really big, you might want to prevent that from happening -- which means not using a DOM parser, but a SAX one.
In PHP, you'll want to take a look at the XMLReader
class.
精彩评论