Search code examples
phphtmlstringinserttags

How to add text in between html tags


I want to add a string in between html tags in php. I'm using php's dom document class and you can only add strings inside html. Here is an example of what I am trying to accomplish

<tag>example</tag><another>sometext</another>

I want to add a string in-between these two tags so it should look like

 <tag>example</tag>STRING<another>sometext</another> 

I want to be able to seperate these tags so I can use the explode function to split every tag in the html page to an array then traverse them for later use.


Solution

  • You can add a textnode without being or having a tag.

    $doc = new DOMDocument();
    
    $tag = $doc->createElement('tag');
    $doc->appendChild($tag);
    $tag->appendChild($doc->createTextNode('example'));
    
    $node = $doc->createTextNode('STRING');
    $doc->appendChild($node);
    
    $another = $doc->createElement('another');
    $doc->appendChild($another);
    $another->appendChild($doc->createTextNode('sometext'));
    
    echo $doc->saveHTML();
    

    will give

    <tag>example</tag>STRING<another>sometext</another>