在PHP中将utf8转换为latin1。255以上的所有字符都将转换为字符引用

在PHP中将utf8转换为latin1。255以上的所有字符都将转换为字符引用,php,character-encoding,Php,Character Encoding,我需要将UTF-8中的文本转换为ISO-8859-1中编码的文本,以便任何不属于ISO-8859-1集合的字符都将转换为字符引用。(例如和#946;) 示例:我想将文本转换为 hello é β 水 进入 我正在用PHP做这一切。我尝试了内置函数、iconv和TINDY以及它们的组合,但仍然无法得到可靠的解决方案 这是我到目前为止所拥有的 // convert any characters fount in the entity table into HTML entities // do n

我需要将UTF-8中的文本转换为ISO-8859-1中编码的文本,以便任何不属于ISO-8859-1集合的字符都将转换为字符引用。(例如
和#946;

示例:我想将文本转换为

hello é β 水
进入

我正在用PHP做这一切。我尝试了内置函数、iconv和TINDY以及它们的组合,但仍然无法得到可靠的解决方案

这是我到目前为止所拥有的

// convert any characters fount in the entity table into HTML entities
// do not double encode entities, do not mess with quotes
// use UTF-8 as character encoding because the page submits UTF-8
$str = htmlentities($str,ENT_NOQUOTES,'UTF-8',false);
//print $str."\n";

// convert text from UTF-8 to ISO-8859-1, 
// characters that cannot be converted will be converted to ?
$str = utf8_decode($str);
//print $str."\n";    

// make string XML valid.
// mainly it converts text entities into numeric entities.
$opts = array(  "output-xhtml"      => true, 
            "output-xml"        => true, 
            "show-body-only"    => true,
            "numeric-entities"  => true,
            "wrap"              => 0,
            "indent"            => false,
            "char-encoding" => 'latin1'
        );
$tidy = tidy_parse_string($str, $opts,'latin1');
tidy_clean_repair($tidy);
$str = tidy_get_output($tidy);      
//print $str."\n";

您将需要多字节支持。特别是:


(使用
htmlentities('helloéβ)不会触及
水', ENT_COMPAT,'UTF-8')
您至少可以将
é
β
转换为HTML实体(命名实体)。这就足够了吗?当然这还不够。最后一个字符是这里的主要问题。请注意,最终结果(XML数据)中不允许实体我希望ISO-8859-1设置为字符。非常感谢。我不知道我以前是如何没有注意到这些函数的。很遗憾,mb函数不是默认编译的一部分,因此并不总是在任何地方都可用。不过,我希望现在大多数服务器上都能看到它们。
// convert any characters fount in the entity table into HTML entities
// do not double encode entities, do not mess with quotes
// use UTF-8 as character encoding because the page submits UTF-8
$str = htmlentities($str,ENT_NOQUOTES,'UTF-8',false);
//print $str."\n";

// convert text from UTF-8 to ISO-8859-1, 
// characters that cannot be converted will be converted to ?
$str = utf8_decode($str);
//print $str."\n";    

// make string XML valid.
// mainly it converts text entities into numeric entities.
$opts = array(  "output-xhtml"      => true, 
            "output-xml"        => true, 
            "show-body-only"    => true,
            "numeric-entities"  => true,
            "wrap"              => 0,
            "indent"            => false,
            "char-encoding" => 'latin1'
        );
$tidy = tidy_parse_string($str, $opts,'latin1');
tidy_clean_repair($tidy);
$str = tidy_get_output($tidy);      
//print $str."\n";
$convmap= array(0x0100, 0xFFFF, 0, 0xFFFF);
$encutf= mb_encode_numericentity($utf, $convmap, 'UTF-8');
$iso= utf8_decode($encutf);