使用PHP DomDocument添加嵌套元素

时间:2015-12-24 03:48:40

标签: php html domdocument

我需要以下面的形式向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识别为嵌套元素而不是纯文本?

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

您可以尝试将其添加为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--;
}