当前结构看起来像
<div class="...">
//more html
<div class="message-right">
<div class="item1"> //more html </div>
<div class="item2"> //more html </div>
<div class="item3"> //more html </div>
</div>
//more html
</div>
我希望能够在“message-right”类中获取 html 内容,并删除最后一个 child 。 (在本例中为“item3”)
我应该留下来自'item1'和'item2'的html
到目前为止我有
$dom = new DomDocument();
@$dom->loadHTML($html);
$finder = new DomXPath($dom);
$classname = "message-right";
$nodes = $finder->query("//*[contains(@class, '$classname')]");
//this is where I am stuck, need to remove the last child, 'item3'
//this returns the html from 'message-right'
$html = $nodes->item(0)->c14n()
最佳答案
获取最后一个子元素(XPath 会更容易)并删除它。
$delete = $finder->query("./*[last()]", $nodes->item(0))->item(0);
$delete->parentNode->removeChild($delete);
根据您真正需要的内容,您可能希望直接使用获取(并随后删除)该元素
//*[contains(@class, '$classname')]/*[last()]
关于php - 删除 DomXPath 中的最后一个子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21792456/