PHP UTF-8 mb_convert_encode and Internet-Explorer


PHP UTF-8 mb_convert_encode and Internet-Explorer

自从几天我读到字符编码,我想让我所有的页面与UTF-8的兼容性。但是当我尝试将用户输入转换为UTF-8时,我卡住了,这适用于所有浏览器,除了Internet-Explorer(一如既往)。

我不知道我的代码出了什么问题,我觉得还行。

  • 我用char编码设置标题
  • 我保存文件在UTF-8 (No BOM)

这种情况只会发生,如果你试图通过$_GET访问页面在internet-Explorer myscript.php?c =友ß当我在我的网站上写下特殊字符时,它们会正确显示。

这是我的代码

// User Input
$_GET['c'] = "äüöß"; // Access URL ?c=äüöß
//--------
header("Content-Type: text/html; charset=utf-8");
mb_internal_encoding('UTF-8');
$_GET = userToUtf8($_GET);
function userToUtf8($string) {
    if(is_array($string)) {
        $tmp = array();
        foreach($string as $key => $value) {
            $tmp[$key] = userToUtf8($value);
        }
        return $tmp;
    }
    return userDataUtf8($string);
}
function userDataUtf8($string) {
    print("1: " . mb_detect_encoding($string) . "<br>"); // Shows: 1: UTF-8
    $string = mb_convert_encoding($string, 'UTF-8', mb_detect_encoding($string)); // Convert non UTF-8 String to UTF-8
    print("2: " . mb_detect_encoding($string) . "<br>"); // Shows: 2: ASCII
    $string = preg_replace('/['xF0-'xF7].../s', '', $string);
    print("3: " . mb_detect_encoding($string) . "<br>"); // Shows: 3: ASCII
    return $string;
}
echo $_GET['c']; // Shows nothing
echo mb_detect_encoding($_GET['c']); // ASCII
echo "äöü+#"; // Shows "äöü+#"

最令人困惑的部分是,它告诉我,这是从UTF-8转换到ASCII…有人能告诉我为什么它不能正确显示我的特殊字符,这里有什么问题吗?或者这是ie浏览器的Bug ?

编辑:

如果我禁用转换,它说,它都是UTF-8,但字符也不会显示给我…它们显示为"????"....

注意:这只发生在Internet-Explorer!

虽然我更喜欢在地址栏中使用urlencoded字符串,但对于您的情况,您可以尝试将$_GET['c']编码为utf8。如:

$_GET['c'] = utf8_encode($_GET['c']);

使用ie11.0.18显示字符的一种方法:

  • 检索字符的Unicode:例如'ü' = 'U+00FC'

  • 根据这篇文章,转换成utf8实体

  • 在转储前使用utf8_decode解码

用'ü'字符说明示例的代码行是:

var_dump(utf8_decode(html_entity_decode(preg_replace("/U'+([0-9A-F]{4})/", "&#x''1;", 'U+00FC'), ENT_NOQUOTES, 'UTF-8')));

总结:为了显示的目的,从Unicode到UTF8,然后在显示之前解码它。

其他资源:检索字符unicode

的post