Ampersand problem in XML when creating a URL String

Chris picture Chris · Jun 29, 2011 · Viewed 13.3k times · Source

I am working with an XML feed that has, as one of it's nodes, a URL string similar to the following:

http://aflite.co.uk/track/?aid=13414&mid=32532&dl=http://www.google.com/&aref=chris

I understand that ampersands cause a lot of problems in XML and should be escaped by using & instead of a naked &. I therefore changed the php to read as follows:

<node><?php echo ('http://aflite.co.uk/track/?aid=13414&amp;mid=32532&amp;dl=http://www.google.com/&amp;aref=chris'); ?></node>

However when this generates the XML feed, the string appears with the full &amp; and so the actual URL does not work. Apologies if this is a very basic misunderstanding but some guidance would be great.

I've also tried using %26 instead of &amp; but still getting the same problem.

Answer

Bernd Ott picture Bernd Ott · Jun 30, 2011

If you are inserting something into XML/HTML you should always use the htmlspecialchars function. this will escape your strings into correct XML syntax.

but you are running into a second problem. your have added a second url to the first one. this need also escaped into url syntax. for this you need to use urlencode.

<node><?php echo htmlspecialchars('http://aflite.co.uk/track/?aid=13414&mid=32532&aref=chris&dl='.urlencode('http://www.google.com/')); ?></node>