Reputation: 15
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.
Upvotes: 0
Views: 1146
Reputation: 420
try this
$content = '<div class="dummy">aaaaaaa</div>';
$DOM_inner_HTML = new DOMDocument();
$DOM_inner_HTML->loadHTML( mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' ) );
$content_node = $DOM_inner_HTML->getElementsByTagName('div')->item(0);
$content_node->textContent = '<span class="newSpan"></span>';
Upvotes: 1
Reputation: 360
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);
Upvotes: 1