Formating strings into XML-safe characters

I am new to php in a sense, I’ve been developing in a different language most my life. Anyway, I want to transform a string into an xml-safe format. Every 30 minutes I run a cron to create a .xml file with the recent data from my database.

Although, some characters in the data contain &, ", ', <, >, etc. Is there a function in php to make these xml safe? If not, then what can I do?

htmlentities() will do the job.

I noticed htmlentities transforms < to <. In terms of XML that would still need to be further transformed to &lt;, would it not?

Not to my knowledge, no.

The entity for & (ie. apersand) is & the entity for < (ie. less than) is < Further transformation will break output. If you want to be really safe, you could transform non-alphabet characters to numeric entities. Tim Burgan has written a handy function “chars_encode” to do this on the htmlentities page on

For a reference on character entities, go grab a copy of the html character entities cheat sheet from