phpdomdocumentcreateelementcreatetextnode

PHP createTextNode with br tag


This is far simpler than I'm making it, I'm sure. I want to create the code:

text<br/>

However you cannot use DOMNode::createElement to add node text to a br as you would with a paragraph:

$doc->createElement('br',$para->nodeValue)

I've also tried creating a text node then adding the break to it. This doesn't work!:

$newelement = $doc->createTextNode($para->nodeValue);
$newelement->appendChild($doc->createElement('br'));
$new_node = $para->parentNode->replaceChild($newelement, $oldelement);

Can anyone advise on the correct method for adding a line with a br tag after it?


Solution

  • $frag=$doc->createDocumentFragment();
    $br=$doc->createElement('br');
    $txt=$doc->createTextNode($para->nodeValue);
    
    $frag->appendChild( $br );
    $frag->appendChild( $txt );
    
    /* etc*/
    $para->parentNode->appendChild( $frag );