Using a regular expression on the XML string works:
$docType = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
$xmlString = preg_replace('/(\<\?xml.+?>)(?!<!DOCTYPE)/s', "\\1\r\n{$docType}\r\n", $xmlString);
I would be interested to know if there is a more elegant why.
Infact, there is 😉. If you have the Tidy extension avialable to you or the option of compiling and/or enabling it, you can get that to do all the work for you. I use this on one of my sites to tidy up use submitted HTML and turn it into XHTML.