在PHP中将UTF-8字符串与7位XML相互转换
时间:2020-03-06 14:34:21 来源:igfitidea点击:
如何将UTF-8字符串(即8位字符串)转换为XML兼容的7位字符串(即具有数字实体的可打印ASCII)或者从中转换?
即一个encode()函数,使得:
encode("“£”") -> "“£”"
decode()也很有用:
decode("“£”") -> "“£”"
PHP的htmlenties()/ html_entity_decode()对没有做正确的事情:
htmlentities(html_entity_decode("“£”")) ->
"“£”"
费力地指定类型会有所帮助,但仍会返回与XML不兼容的命名实体,而不是数字实体:
htmlentities(html_entity_decode("“£”", ENT_QUOTES, "UTF-8"), ENT_QUOTES, "UTF-8") ->
"“£”"
解决方案
这是一个变通办法,但我对iconv()有所了解,但我认为它不会给我们数字实体(未经测试)
function decode( $string )
{
$doc = new DOMDocument( "1.0", "UTF-8" );
$doc->LoadXML( '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<x />', LIBXML_NOENT );
$doc->documentElement->appendChild( $doc->createTextNode( $string ) );
$output = $doc->saveXML( $doc );
$output = preg_replace( '/<\?([^>]+)\?>/', '', $output );
$output = str_replace( array( '<x>', '</x>' ), array( '', '' ), $output );
return trim( $output );
}
但是,我对此进行了测试。我稍后可能会做相反的事情,只是不要屏住呼吸;-)
mb_encode_numericentity完全可以做到这一点。

