How do I remove all the li elements except the first in PHP?
<div class="category">
<ul class="products">
<li>{nested child elements}</li>
<li>{nested child elements}</li>
<li>{nested child elements}</li>
</ul>
</div>
The code above is generated by another script via a function.
The result should be like this:
<div class="category">
<ul class="products">
<li>{nested child elements}</li>
</ul>
</div>
UPDATE: Sorry guys the "category" is a class not an ID.
In repay to Yoshi, ul.products has siblings but I didn't include them in my post. Would that affect the query?
This is how my code looks like with Yoshi's code added:
class Myclass {
function prin_html() {
$content = get_code();
$dom = new DOMDocument;
$dom->loadXml($content);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//li[position()>1]') as $liNode) {
$liNode->parentNode->removeChild($liNode);
}
echo $dom->saveXml($dom->documentElement);
}
}
It sill prints the non-filtered html code...