使用 PHP DomDocument 添加嵌套元素

Using PHP DomDocument to add nested elements

我需要按以下形式向我的 DOM 添加一个元素:

<div class='spelling'>Are you sure "<span class='anotherclass'>abc</span>" is a verb?</div>

我的尝试如下:

$node = $divs->item($i);
if ($node->getAttribute('class') == 'card') {
    $ele=$dom->createElement('div');
    $ele->textContent = 'Are you sure "<span class="anotherclass">' . $term . '</span>" is a verb? Try looking it up in our dictionary.';
    $ele->setAttribute('class', 'spelling');
    $node->parentNode->insertBefore($ele,$node);
    $node->parentNode->removeChild($node);
    $i--;
}

这确实成功添加了新的div;但是,它无法将 span 添加为元素。相反,它只是将 span 作为文本的一部分添加到 div 中。如何让 PHP 将 span 识别为嵌套元素而不是纯文本?

你可以试试:How to insert HTML to PHP DOMNode?

您可以尝试将其添加为 CDATA 部分,是否仍然适合您?

$node = $divs->item($i);
if ($node->getAttribute('class') == 'card') {
    $ele=$dom->createElement('div');

    // append a CDATA section rather than setting the content
    $ele->appendChild($ele->ownerDocument->createCDATASection('Are you sure "<span class="anotherclass">' . $term . '</span>" is a verb? Try looking it up in our dictionary.');

    $ele->setAttribute('class', 'spelling');
    $node->parentNode->insertBefore($ele,$node);
    $node->parentNode->removeChild($node);
    $i--;
}