- preg_replace_callback: documentation ( source)
- trim: documentation ( source)
<?php
$xml = new SimpleXMLElement('<data/>');
$value="This & That";
$value = preg_replace_callback('/&[^; ]{0,6}.?/', "((substr('\\0',-1) == ';') ? '\\0' : '&'.substr('\\0',1))", trim($value));
$xml->addChild('header', $value);