使用 DOMDocument 和 DOMXPath 正确删除 PHP 中的子元素

发布于 2024-10-03 14:04:46 字数 398 浏览 0 评论 0原文

这是之前的另一个问题,但我们不会谈论这个。我正在第三方 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌化 2024-10-10 14:04:46

而不是:

$xpath->query("//span", $name)

Do:

$xpath->query("span", $name)

//nodename 匹配所有节点,无论其父节点是什么。当您的查询以 // 开头时,$contextnode 将被忽略。

Instead of:

$xpath->query("//span", $name)

Do:

$xpath->query("span", $name)

//nodename matches all nodes no matter what their parent is. $contextnode is ignored when your query starts with //.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文