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.