I am working on project in flex 3
, where user enters some text which is to be stored in a mysql
database and shown later. I am using XML
for data transfer from flex to php and vice-versa. SimpleXMLElement
in php
is being used to create the XML
. The problem is the XML
breaks on special characters.
Here is sample code:
FLEX:
var someXML:XML = <root><data>somedata</data><data>...</data> ... </root>
var data:Object = {};
data.xmlData = someXML;
saveDataService.send(data);
Here somedata
is the data entered by the user. In php
, I extract the someXML
using SimpleXMLElement
and store it to mysql
. There is no problem till here. Even if somedata
has special characters its working fine and data is stored properly.
Now, in the other case, getting data from database and showing in flex, the response from the php breaks with an error:
SimpleXMLElement::addChild() [simplexmlelement.addchild]: unterminated entity reference开发者_运维技巧
I tried using urlencode
in php, and decodeURI
function in flex, but the decoded string is not the same, few special characters are still %xy
after decoding.
How do I solve this problem?
In XML an &
starts an entity. The ;
ends it. When you have a literal &
you will get an unterminated entity reference. Change all &
to &
that are not entities already, e.g. dont change >
to &gt;
. Or put somedata into CDATA sections.
First off, if you have a dangling &
character in your xml, then you have an xml syntax error. Its nothing to do with SimpleXML or any other parser complaining. I'd suggest you fix this even before the data gets into the db, better yet, before it is sent to the php service.
Gordon's suggestion works, for &
at least. You'll likely face the problem with other characters like <
, "
etc., later on and you'll be facing pretty much the same thing.
I'd suggest you do a htmlentities
like operation on the text data in side the xml, not including the xml tags themselves. Following code taken from http://thingsthatwork.net/index.php/2008/06/26/html-entities-and-actionscript/
XML(new XMLNode(XMLNodeType.TEXT_NODE, "content with special chars like & and others")).toXMLString();
Haven't tested the above, but it should return you the sanitized content that you can put into xml. It should effectively turn &
chars into &
, all of them. i.e., This should also turn occurences of >
to &gt;
, so be wary of that.
Let me know if you need anything else. Also, how ya doin' man!? ;)
Edit: Oh, keep in mind, it has been long time since I used php, so some of the info above might be a bit off. Please correct me guys. Thanks.
Try escaping your data with htmlspecialchars before passing it to SimpleXMLElement::addChild
精彩评论