使用PHP DomDocument添加嵌套元素

使用PHP DomDocument添加嵌套元素,php,html,domdocument,Php,Html,Domdocument,我需要以以下形式向我的DOM添加一个元素: <div class='spelling'>Are you sure "<span class='anotherclass'>abc</span>" is a verb?</div> 你确定“abc”是动词吗? 我的尝试如下: $node = $divs->item($i); if ($node->getAttribute('class') == 'card') { $ele=$d

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

<div class='spelling'>Are you sure "<span class='anotherclass'>abc</span>" is a verb?</div>
你确定“abc”是动词吗?
我的尝试如下:

$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--;
}
$node=$divs->item($i);
如果($node->getAttribute('class')=='card'){
$ele=$dom->createElement('div');
$ele->textContent='你确定“.$term.”是动词吗?试着在我们的字典里查一下;
$ele->setAttribute('class','spelling');
$node->parentNode->insertBefore($ele,$node);
$node->parentNode->removeChild($node);
$i--;
}

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

您可以尝试:

如果仍然适用,您可以尝试将其添加为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--;
}
$node=$divs->item($i);
如果($node->getAttribute('class')=='card'){
$ele=$dom->createElement('div');
//附加CDATA节,而不是设置内容
$ele->appendChild($ele->ownerDocument->createCDATASection('你确定“.$term.”“是动词吗?试着在我们的字典里查一下。”);
$ele->setAttribute('class','spelling');
$node->parentNode->insertBefore($ele,$node);
$node->parentNode->removeChild($node);
$i--;
}

我使用了
insertBefore
,因为我确实需要新的
div
放在
卡片
div之前。我正在努力解决的是嵌套在新
div
中的
span
。误解,抱歉。请尝试我链接到的其他答案。