开发者

How to output XML safe string in PHP?

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 d开发者_Go百科on't know how to ensure that. Is there some functions/libraries to ensure everything is well formed?


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


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)
else
    return str_replace(array('&','>','<'), array('&amp;','&gt;','&lt;'), $s);
    // SAME AS htmlspecialchars($s,ENT_NOQUOTES)
}

// example of SAFE XML CONSTRUCTION
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 .= '/>';
else
    $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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜