Search code examples
phplibxml2

Wrap tag in Libxml


I am currently build on top of an existing libxml code and couldn't find a detailed documentation.

Is it possible to wrap a tag around a node?

I thought this would work:

$tags = $doc->getElementsByTagName( 'pre' );

foreach( $tags as $tag ):

    $handler = $doc->createElement( 'div' );
    $handler->setAttribute( 'class', 'pre_wrapper' );
    $newnode = $handler->appendChild( $tag );

    $tag->replaceNode( $newnode );

endforeach;

Solution

  • The problem is that $handler->appendChild($tag) unlinks the element $tag from its original location, so the following replaceNode doesn't have the desired effect. This means that you have to swap the order of calls. Also, I couldn't find a replaceNode method, but there's replaceChild which has to be invoked on the parent node:

    # Create wrapper element
    $handler = $doc->createElement('div');
    $handler->setAttribute('class', 'pre_wrapper');
    # Replace wrapped element with wrapper
    $tag->parentNode->replaceChild($handler, $tag);
    # Move wrapped element into wrapper
    $handler->appendChild($tag);
    

    Try it online!