Generating XML document in PHP (escape characters)

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
    );
}

Leave a Comment