Last active
December 6, 2021 01:26
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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