XML error at ampersand (&)

$string =htmlspecialchars($string,ENT_XML1);

is the most universal way to solve all encoding errors (IMHO better that write custom functions + there is no point to solve just &).

Credit: Put Wrikken's and joshweir's comment as answer to be more visible.


& in XML starts an entity. As you haven't defined an entity &WhateverIsAfterThat an error is thrown. You should escape it with &.

$string = str_replace('&', '&', $string);

How do I escape ampersands in XML

To escape the other reserved characters:

function xmlEscape($string) {
    return str_replace(array('&', '<', '>', '\'', '"'), array('&amp;', '&lt;', '&gt;', '&apos;', '&quot;'), $string);
}