Questions
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?
Answers
http://www.php.net/manual/en/book.dom.php
http://www.php.net/manual/en/book.dom.php
Edit: This was criticized by @Tchalvak:
The DOM object creates a full XML document, it doesn t easily lend itself to just encoding a string on it s own.
Which is wrong, DOMDocument can properly output just a fragment not the whole document:
$doc->saveXML($fragment);
which gives:
Test & <b> and encode </b> :)
Test &amp; <b> and encode </b> :)
as in:
$doc = new DOMDocument();
$fragment = $doc->createDocumentFragment();
// adding XML verbatim:
$xml = "Test & <b> and encode </b> :)
";
$fragment->appendXML($xml);
// adding text:
$text = $xml;
$fragment->appendChild($doc->createTextNode($text));
// output the result
echo $doc->saveXML($fragment);
http://eval.in/10247
http://eval.in/10247
Source
License : cc by-sa 3.0
http://stackoverflow.com/questions/3957360/generating-xml-document-in-php-escape-characters
Related