我正在从PHP脚本生成XML文档,并且需要对XML特殊字符进行转义。我知道应该转义的字符列表;但是正确的方法是什么呢?
字符应该只使用反斜杠(\')进行转义,还是正确的方式?有没有什么内置的PHP函数可以帮我处理这个问题?
发布于 2010-10-18 16:00:46
使用XML类生成整个DOM文档。它将处理我们甚至不想关心的编码和解码。
编辑:@Tchalvak批评了:
XML对象创建了一个完整的
文档,它不能轻易地单独编码一个字符串。
这是错误的,DOMDocument可以只正确地输出一个片段,而不是整个文档:
$doc->saveXML($fragment);这就给出了:
Test & <b> and encode </b> :)
Test &amp; <b> and encode </b> :)如下所示:
$doc = new DOMDocument();
$fragment = $doc->createDocumentFragment();
// adding XML verbatim:
$xml = "Test & <b> and encode </b> :)\n";
$fragment->appendXML($xml);
// adding text:
$text = $xml;
$fragment->appendChild($doc->createTextNode($text));
// output the result
echo $doc->saveXML($fragment);请参阅Demo
发布于 2010-10-18 16:26:40
我创建了一个简单的函数,它使用XML中的five "predefined entities"进行转义:
function xml_entities($string) {
return strtr(
$string,
array(
"<" => "<",
">" => ">",
'"' => """,
"'" => "'",
"&" => "&",
)
);
}使用示例Demo
$text = "Test & <b> and encode </b> :)";
echo xml_entities($text);输出:
Test &amp; <b> and encode </b> :)使用str_replace也可以达到类似的效果,但由于使用了双重替换(未经测试,不推荐),因此很脆弱:
function xml_entities($string) {
return str_replace(
array("&", "<", ">", '"', "'"),
array("&", "<", ">", """, "'"),
$string
);
}发布于 2013-02-15 15:46:16
那么htmlspecialchars()函数呢?
htmlspecialchars($input, ENT_QUOTES | ENT_XML1, $encoding);注意:只有在安装了PHP5.4.0或更高版本的情况下,ENT_XML1标志才可用。
具有这些参数的htmlspecialchars()将替换以下字符:
& (与号)变成&" (双引号)变成"' (单引号)变成'< (小于)变成<> (大于)变成>您可以使用get_html_translation_table()函数获取转换表。
https://stackoverflow.com/questions/3957360
复制相似问题