This question already has answers here:
How to get innerHTML of DOMNode?

(8个答案)


3年前关闭。




如何更改php DOMElement的innerHTML?

最佳答案

另一个解决方案:

1)从要插入的HTML字符串中创建新的DOMDocumentFragment
2)通过删除元素的子节点来删除元素的旧内容;
3)将DOMDocumentFragment附加到我们的元素。

function setInnerHTML($element, $html)
{
    $fragment = $element->ownerDocument->createDocumentFragment();
    $fragment->appendXML($html);
    while ($element->hasChildNodes())
        $element->removeChild($element->firstChild);
    $element->appendChild($fragment);
}

或者,我们可以将其元素替换为其clean copy,然后将DOMDocumentFragment附加到此克隆中。
function setInnerHTML($element, $html)
{
    $fragment = $element->ownerDocument->createDocumentFragment();
    $fragment->appendXML($html);
    $clone = $element->cloneNode(); // Get element copy without children
    $clone->appendChild($fragment);
    $element->parentNode->replaceChild($clone, $element);
}

测试:
$doc = new DOMDocument();
$doc->loadXML('<div><span style="color: green">Old HTML</span></div>');
$div = $doc->getElementsByTagName('div')->item(0);
echo $doc->saveHTML();

setInnerHTML($div, '<p style="color: red">New HTML</p>');
echo $doc->saveHTML();

// Output:
// <div><span style="color: green">Old HTML</span></div>
// <div><p style="color: red">New HTML</p></div>

09-25 21:35