
My site occasionally serves invalid XML. This is an unfortunate business. The reasons are quite convoluted, but are to do with the way that you can't use CDATA sections inside attributes (Kosso will understand what I'm talking about).
So sometimes unencoded stuff is sent to the browser, or, as this morning, an unclosed span element.
I decided to fix it by writing some code that would detect whether what's about to be sent is valid XML. Simple enough. Just load it all into a DOM tree, and if it chokes on loading, it's not valid XML - then serve it as text/html to invoke the usually slower XHTML parsers.
Here's the code. It's done with PHP output control and the DOM - so PHP5 only, folks. You do use PHP5, right?