Search code examples
phpdomdocument

Prepend HTML text using DOMDocument without parent container


Let's say I have <p>Text</p>

I'd like to create a function using DOMDocument to be able to insert text, eg:

insertText('<p>Text</p>', '<strong>1.</strong> ')

So that the result was <p><strong>1.</strong> Text<p>

I'm already accessing this paragraph tag, so I think I'm almost there, I just cannot figure out how to append plain text that can be read as HTML

$dom = new DOMDocument();
$question_paragraphs = array();
$dom->loadHTML($str);
$par = $dom->getElementsByTagName('p');
if ($par->length == 1) {
    $par->item(0)->setAttribute("class", "first last");
###
### How do I do this here?
###
}

Is it possible to inject text this way?


Solution

  • You can get use the method insertBefore (Official Documentation) as follows

    1. You create your strong element
    2. You insert this node before the text node
    $span = $dom->createElement('strong', '1.');
    $par->item(0)->insertBefore($span, $par->item(0)->firstChild);
    

    Please note that the second parameter of the insertBefore function is the child to which you want to prepend your tag. So in this case you can use firstChild as your <p> only contains the Text.

    This will finally output

    <p class="first last"><span>1.</span>Text</p>