我使用此函數對所有 XML 實體以及所有 XML 中未定義的 &something; 進行編碼,例如 ™。
您也可以使用我的解碼函數來解碼您編碼的內容。
我的函數有點像 htmlentities。
如果您想將其他字串排除在編碼之外,您也可以將它們新增到陣列中。
<?php
function xml_entity_decode($text, $charset = 'Windows-1252'){
$text = html_entity_decode($text, ENT_COMPAT, $charset);
$text = html_entity_decode($text, ENT_COMPAT, $charset);
return $text;
}
function xml_entities($text, $charset = 'Windows-1252'){
$text = htmlentities($text, ENT_COMPAT, $charset, false);
$arr_xml_special_char = array(""","&","'","<",">");
$arr_xml_special_char_regex = "(?";
foreach($arr_xml_special_char as $key => $value){
$arr_xml_special_char_regex .= "(?!$value)";
}
$arr_xml_special_char_regex .= ")";
$pattern = "/$arr_xml_special_char_regex&([a-zA-Z0-9]+;)/";
$replacement = '&${1}';
return preg_replace($pattern, $replacement, $text);
}
?>