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开发者_如何学JAVA 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...
Try:
$dom = new DOMDocument;
$dom->loadHtml('<div id="category">
<ul class="products">
<li>{nested child elements}</li>
<li>{nested child elements}</li>
<li>{nested child elements}</li>
</ul>
</div>');
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//li[position()>1]') as $liNode) {
$liNode->parentNode->removeChild($liNode);
}
$output = '';
foreach ($xpath->query('//body/*') as $child) {
$output .= $dom->saveXml($child);
}
Output:
<div id="category">
<ul class="products">
<li>{nested child elements}</li>
</ul>
</div>
You could use DOMDocument.
$dom = new DOMDocument;
$dom->loadHTML($html);
$ul = $dom->getElementById('category')->getElementsByTagName('ul')->item(0);
foreach($ul->getElementsByTagName('li') as $index => $li) {
if ($index == 0) {
continue;
}
$ul->removeChild($li);
}
精彩评论