XML Entities in PHP

Because htmlentities() doesn’t even come close.

This small file contains 4 functions (2 of which are taken from the PHP manual, credit given!) which will allow you to encode and decode entities from ASCII/unicode strings in either decimal or hexadecimal format for use in valid XML documents.

The xml_entity_decode() function accepts an optional second parameter to allow non-standard XML entities (that may have been specified in your schema) in the format:

  // 'entity' => 'char'
  'amp' => '&',
  'lt' => '<',
  'gt' => '>',
  'apos' => '\'',
  'quot' => '"'

Example usage:


$s = 'This should be safe, but don\'t assume!
'; print ''.xmlentities($s).''; // outputs: <strong>This</strong> should be safe, but don't assume!<br/>

You can get the script here, or there’s a demo here too.

2 Replies to “XML Entities in PHP”

  1. Thanks for this! This was driving me nuts, in the installation I have (5.2.x) it seemed all but impossible to make a decent xmlentities converison. I found this page throught google and gave it a try, works like a charm :). Cheers!

    1. No problem Erik, glad you found it useful! It’s probably in need of an update to handle unicode characters and such, but I think it still serves is purpose for the moment!

      Thanks for commenting!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.