Take the 2-minute tour ×

I am doing some stuff that needs to output xml(utf-8) using PHP scripts. It has strict format requirements, which means the xml must be well formed. I know 'htmlspecialchars' to escape, but I don't know how to ensure that. Is there some functions/libraries to ensure everything is well formed?

share|improve this question
add comment

2 Answers

You can use PHP DOM or SimpleXML. These will also handle escaping for you.

share|improve this answer
add comment

The Matthew answer indicates the "framework" for produce your XML code.

If you need only simple functions to work with your XML class or do "XML-translations", here is a didactic example (replace xmlsafe function by htmlspecialchars function).

PS: remember that safe UTF-8 XML not need a full entity encode, you need only htmlspecialchars... Not require all special characters to be translated to entities.

Only 3 or 4 characters need to be escaped in a string of XML content: >, <, &, and optional ". See also the XML specification, http://www.w3.org/TR/REC-xml/ "2.4 Character Data and Markup" and "4.6 Predefined Entities".

The following PHP function will make a XML completely safe:

// it is for illustration, use htmlspecialchars($s,flag).
function xmlsafe($s,$intoQuotes=0) {
if ($intoQuotes)
    return str_replace(array('&','>','<','"'), array('&amp;','&gt;','&lt;','&quot;'), $s);
    // SAME AS htmlspecialchars($s)
    return str_replace(array('&','>','<'), array('&amp;','&gt;','&lt;'), $s);
    // SAME AS htmlspecialchars($s,ENT_NOQUOTES)

function xmlTag( $element, $attribs, $contents = NULL) {
$out = '<' . $element;
foreach( $attribs as $name => $val )
   $out .= ' '.$name.'="'. xmlsafe( $val,1 ) .'"';  // convert quotes
if ( $contents==='' || is_null($contents) )
    $out .= '/>';
    $out .= '>'.xmlsafe( $contents )."</$element>";  // not convert quotes
return $out;

In a CDATA block you not need use this function... But, please, avoid the indiscriminate use of CDATA.

share|improve this answer
add comment

Your Answer


