Skip to content

Instantly share code, notes, and snippets.

@dnaber-de
Last active December 6, 2021 01:26
Show Gist options
  • Save dnaber-de/6f68db0ea614a6f979d9 to your computer and use it in GitHub Desktop.
Save dnaber-de/6f68db0ea614a6f979d9 to your computer and use it in GitHub Desktop.
Dissolving a DOM Node and moving all child nodes one level up
<?php
$html = <<<HTML
<table>
<tr>
<td>Foo with some <span>makrup</span> inside</td>
<td>Bar also <div>with <em>some</em></div> markup</td>
</tr>
</table>
HTML;
$dom = new DOMDocument;
$dom->loadXML( $html );
// remove the <td>-Tags and keep everything else
$tdList = $dom->getElementsByTagName( 'td' );
while( $tdList->length > 0 ) {
$td = $tdList->item( 0 );
$fragment = $dom->createDocumentFragment();
while( $td->childNodes->length > 0 )
$fragment->appendChild( $td->childNodes->item( 0 ) );
$td->parentNode->replaceChild( $fragment, $td );
}
var_dump( $dom->saveHTML() );
/**
* string(141) "<table>
* <tr>
* Foo with some <span>makrup</span> inside
* Bar also <div>with <em>some</em></div> markup
* </tr>
* </table>
* "
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment