Ampersand problem in XML when creating a URL String

拥有回忆 提交于 2020-01-03 18:01:09

问题


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.


回答1:


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>



回答2:


&amp; is correct for escaping ampersands in an XML document. The example you've given should work.

You state that it doesn't work, but you haven't stated what application you're using, or in what way it doesn't work. What exactly happens when you click the link? Do the &amp; strings end up in the browser's URL field? If that's the case, it sounds like a fault with the software you've viewing the XML with. Have you tried looking at the XML in another application to see if the problem is consistent?

To answer the final part of your question: %26 would definitely not work for you -- this would be what you'd use if your URL parameters needed to contain ampersands. Say for example in aref=chris, if the name chris were to an ampersand (lets say the username was chris&bob), then that ampersand would need to be escaped using %26 so that the URL parser didn't see it as starting a new URL parameter.

Hope that helps.



来源:https://stackoverflow.com/questions/6519457/ampersand-problem-in-xml-when-creating-a-url-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!