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?
XML escape characters There are only five: " " ' ' < < > > & & Escaping characters depends on where the special character is used. The examples can be validated at the W3C Markup Validation Service.
In PHP, an escape sequence starts with a backslash \ . Escape sequences apply to double-quoted strings. A single-quoted string only uses the escape sequences for a single quote or a backslash.
I created simple function that escapes with the five "predefined entities" that are in XML:
function xml_entities($string) { return strtr( $string, array( "<" => "<", ">" => ">", '"' => """, "'" => "'", "&" => "&", ) ); }
Usage example Demo:
$text = "Test & <b> and encode </b> :)"; echo xml_entities($text);
Output:
Test &amp; <b> and encode </b> :)
A similar effect can be achieved by using str_replace
but it is fragile because of double-replacings (untested, not recommended):
function xml_entities($string) { return str_replace( array("&", "<", ">", '"', "'"), array("&", "<", ">", """, "'"), $string ); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With