Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating XML document in PHP (escape characters)

Tags:

php

xml

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?

like image 279
Tomas Jancik Avatar asked Oct 18 '10 07:10

Tomas Jancik


People also ask

How do you escape special characters in XML?

XML escape characters There are only five: " &quot; ' &apos; < &lt; > &gt; & &amp; Escaping characters depends on where the special character is used. The examples can be validated at the W3C Markup Validation Service.

How do I escape a character in PHP?

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.


1 Answers

I created simple function that escapes with the five "predefined entities" that are in XML:

function xml_entities($string) {     return strtr(         $string,          array(             "<" => "&lt;",             ">" => "&gt;",             '"' => "&quot;",             "'" => "&apos;",             "&" => "&amp;",         )     ); } 

Usage example Demo:

$text = "Test &amp; <b> and encode </b> :)"; echo xml_entities($text); 

Output:

Test &amp;amp; &lt;b&gt; and encode &lt;/b&gt; :) 

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("&amp;", "&lt;", "&gt;", "&quot;", "&apos;"),          $string     ); } 
like image 94
Tomas Jancik Avatar answered Sep 23 '22 13:09

Tomas Jancik