tags:

views:

53

answers:

4

I'm generating XML document from PHP script and I need to escape the XML special characters... I know the list of characters that should be escaped, but what is the correct way to do it?

Should the characters be escaped just with backslash (\') or what is the proper way? Is there any builtin function in PHP that can handle this for me?

A: 

Do you mean XML entities? If so, you might want to use the htmlspecialchars() function.

Frédéric Hamidi
this function escapes more entities than is needed for XML and it causes me errors in XML validator (I'm using czech language and diactritics, which is the main problem)
Tomas Jancik
You want [htmlspecialchars()](http://www.php.net/manual/en/function.htmlspecialchars.php) then. I'll update my answer.
Frédéric Hamidi
A: 

You can use this methods: http://php.net/manual/en/function.htmlentities.php

In that way all entities (html/xml) are escaped and you can put your string inside XML tags

Alois Cochard
+1  A: 

Use the DOM classes to generate XML. It will handle encodings and decodings that we don't even want to care about.

Ionuț G. Stan
A: 

I created simple function that escapes the 5 xml entities... feel free to try and use it

or let me know if there are any issues

function xmlentities($string) { return strtr($string, array("<", ">", "\"", "'", "&"), array("<", ">", """, "'", "&")); }

Tomas Jancik