- rtrim: documentation ( source)
- simplexml_load_string: documentation ( source)
- dom_import_simplexml: documentation ( source)
- explode: documentation ( source)
<?php declare(strict_types=1);
$buffer=<<<XML
<description><![CDATA[<div id="2" style="all: inherit;"><span style='font-size: 40px'>Testing123</span></div>]]></description>
XML;
$asString = static function (SimpleXMLElement $el) {
return rtrim(explode("\n", $el->asXML(), 2)[1]);
};
$makeCdata = static function (SimpleXMLElement $el, string $data) {
$el[0] = null;
if ($n = dom_import_simplexml($el)) {
$cd = $n->ownerDocument->createCDATASection($data);
$n->appendChild($cd);
}
};
$xml = simplexml_load_string($buffer);
$cdata = simplexml_load_string((string)$xml);
foreach ($cdata->xpath('@*[name(.) != "id"]|*/@*') as $attribute)
unset($attribute[0])
;
$makeCdata($xml, $asString($cdata));
echo $xml->asXML();