Search code examples
phphtmldomdomdocument

How to change a HTML element's text to another element in PHP?


As the title says, I'd like to change a DOM element's textContent to a span, using PHP. Like from this:

<div class="dummy">Here is my content.</div>

to this:

<div class="dummy"><span class="newSpan"></span></div>

I've tried to set the content to empty like

$sourceDOMElement->nodeValue = ""; //OR
$sourceDOMElement->textContent = "";

But none worked for some reason. After this, I'd like to append a new child to the element with the new span I'd like to insert.

How could I make this work? Thanks in advance!

EDIT: Here's my whole code, where I have to do this.


Solution

  • You can set the nodeValue property if you want to set text content of an element like this

    $el = $dom->getElementById('foo');
    $el->nodeValue = 'hello world';
    

    this automatically escapes < and >, so you can't insert HTML like this.

    so to do that u can go with :

    DOMDocument::createDocumentFragment:
    
    $frag = $dom->createDocumentFragment();
    $frag->appendXML('<h1>foo</h1>');
    $el->appendChild($frag);