I'm generating an XML document from a PHP script and I need to escape the XML special characters. I know the list of characters that should be escaped; but what is the correct way to do it?
Should the characters be escaped just with backslash (') or what is the proper way? Is there any built-in PHP function that can handle this for me?
Use the DOM classes to generate your whole XML document. It will handle encodings and decodings that we don't even want to care about.
Edit: This was criticized by @Tchalvak:
Which is wrong, DOMDocument can properly output just a fragment not the whole document:
which gives:
as in:
See Demo