I suggested using XPath for this in my original comment, however, I've been playing around with some XPath expressions for this using a combination of following-sibling
and preceding-sibling
but I can't get it to work properly with this XML structure.
A bit of a hacky way of doing this is by just fetching everything after a given page number, and stopping when you find the next <page />
or <endpages />
element:
$dom = new DOMDocument("1.0", "UTF-8");
$dom->load($xmlFile);
$xp = new DOMXPath($dom);
$pageNo = 2;
$list = $xp->query("/book/page[@n='" . $pageNo . "']/following-sibling::*");
foreach ($list as $node) {
if ($node->nodeName == 'page' || $node->nodeName == 'endpages') {
break;
}
echo $node->textContent . "<br />"; // <entry /> node
}
I'm quite sure this will not perform very well if you have a lot of pages in the XML file and you're trying to fetch only the elements of page one, but in terms of lines of code this is overseeable and maybe someone else has some ideas on how to optimise the XPath expression.