简体   繁体   中英

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.

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);

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>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM