使用 DOMDocument 和 DOMXPath 正确删除 PHP 中的子元素
这是之前的另一个问题,但我们不会谈论这个。我正在第三方 HTML 文档中隔离多个部分。当匹配一些时,我需要从结果中删除某些标签。我在 SO 上找到的代码是:
$name = $xpath->query("//div[@class='leftColBig']//h3")->item(0);
// remove <span>
foreach($xpath->query("//span", $name) as $node)
$node->parentNode->removeChild($node);
这有一个不幸的副作用,不仅从 $name 中删除子项,而且还删除整个 DOMDocument :( 我怎样才能将removeChild仅隔离到我使用查询找到的部分。
This was previous another question, but we won't talk about that. I am isolating a number of sections in a third party HTML document. When matching some, I need to remove certain tags from the result. The code I found for this on SO was:
$name = $xpath->query("//div[@class='leftColBig']//h3")->item(0);
// remove <span>
foreach($xpath->query("//span", $name) as $node)
$node->parentNode->removeChild($node);
This has the unfortunate side effect of not just deleting the child from $name, but the entire DOMDocument :( How can I isolate the removeChild just to the section I found using the query.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
而不是:
Do:
//nodename
匹配所有节点,无论其父节点是什么。当您的查询以//
开头时,$contextnode 将被忽略。Instead of:
Do:
//nodename
matches all nodes no matter what their parent is. $contextnode is ignored when your query starts with//
.