gpt4 book ai didi

PHP: "Couldn' t 获取 DOMElement。节点不再存在于"using DOMXpath

转载 作者:行者123 更新时间:2023-12-05 05:05:00 33 4
gpt4 key购买 nike

我有一些包含以下内容的 HTML:

<div class="test">
Outer
<div class="test">Inner 1</div>
<div class="test">Inner 2</div>
</div>

我正在对这些元素的内容执行 str_replace():

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXpath($dom);

foreach($xpath->query("//div[@class='test']") as $node) {
$node->nodeValue = str_replace(" ", "X", $node->nodeValue);
}

这应该用“X”替换所有空格。

但它会导致这个错误:

Warning: Couldn't fetch DOMElement. Node no longer exists in /path/to/my/file.php on line 63

如果只有一个嵌套的 div,它会起作用:

<div class="test">
Outer
<div class="test">Inner 1</div>
</div>

为什么会发生这种情况,我该如何让它发挥作用?

最佳答案

尝试改变

foreach($xpath->query("//div[@class='test']") as $node) 

foreach($xpath->query('//div[@class="test"]//div[@class="test"]') as $node)

根据评论编辑:

假设外部元素中有一个空格(即它的“Outer 1:”):

<?php
$string = <<<XML
<div class="test">
Outer 1
<div class="test">Inner 1</div>
<div class="test">Inner 2</div>
</div>
XML;
$dom = new DOMDocument();
$dom->loadHTML($string);
$xpath = new DOMXpath($dom);

foreach($xpath->query('//div[@class="test"]//text()') as $node) {
$nnode = trim($node->nodeValue);

echo $nnode = str_replace(" ", "X", $nnode);
}

关于PHP: "Couldn' t 获取 DOMElement。节点不再存在于"using DOMXpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60779753/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com