tags:

views:

102

answers:

3

I am responding to an AJAX call by sending it an XML document through PHP echos. In order to form this XML document, I loop through the records of a database. The problem is that the database includes records that have '<' symbols in them. So naturally, the browser throws an error at that particular spot. How can this be fixed?

+8  A: 

By either escaping those characters with htmlspecialchars, or, perhaps more appropriately, using a library for building XML documents, such as DOMDocument or XMLWriter.

Another alternative would be to use CDATA sections, but then you'd have to look out for occurrences of ]]>.

Take also into consideration that that you must respect the encoding you define for the XML document (by default UTF-8).

Artefacto
+1 for *using a library for building XML documents*
Gordon
+2  A: 

1) You can wrap your text as CDATA like this:

<mytag>
    <![CDATA[Your text goes here. Btw: 5<6 and 6>5]]>
</mytag>

see http://www.w3schools.com/xml/xml_cdata.asp

2) As already someone said: Escape those chars. E.g. like so:

5&lt;6 and 6&gt;5
Elvith
*oops* I overlooked that CDATA was already mentioned in the previous answer
Elvith
You made it very clear what I needed to do, so I appreciate that, regardless of whether it was already mentioned. I ended up using your solution for a quick fix, but the best practice would probably be to use XMLWriter has Artefacto mentioned, so I'm giving the best answer to him.
JayD3e
A: 

If at all possible, its always a good idea to create your XML using the XML classes rather than string manipulation - one of the benefits being that the classes will automatically escape characters as needed.

Ed Schembor