解码 PHP 中的字符串时出现意外行为(来自 AJAX POST 调用)

Unexpected behaviour while decoding strings in PHP (from AJAX POST call)

我有一些 javascript 可以将 JSON 格式的数据通过 POST 格式发送到 PHP 脚本。

使用 "usual" 个字符一切正常,但我发现在使用例如带有“à”等重音符号的元音时会出现不一致。我想问问有没有人对如何解决这个问题有建议。

这是Javascript:

$.ajax({
        contentType: 'application/json',
        data: JSON.stringify({
            "action": params.action,
            "username": params.username,
            "page": params.page,
        }),
        processData: false,
        //dataType: 'json',
        url: "/w/ImolaCustom/SudoAutoedit.php",
        type: 'POST',
        success: function(data) { 
            ...
        }
    });

在 PHP 方面,我这样做:

$theData = json_decode(file_get_contents('php://input')), true);

如果我发送如下内容,问题就会出现:

params.page = "Società sportiva Bridge";

随着 $theData['page'] 变成 "Societ\xc3\xa0 sportiva Bridge"

如果我使用 utf8_decode($theData['page']) (或者如果我在从 php://input 传递的字符串上使用它之前 json_decoding我得到的是 "Societ\xe0 sportiva Bridge"。

我尝试了不同的转换函数,如 iconv()、mb_convert_variables() 和 mb_convert_encoding(),将 UTF-8 转换为 ISO-8859-1,结果与上述相同。

我还尝试使用 encodeURIComponent() 或 escape() 对字符串客户端进行编码。 PHP 收到正确的字符串(分别为 "Societ%C3%A0%20sportiva%20Bridge" 和 "Societ%E0%20sportiva%20Bridge"),但在使用 rawurldecode() 解码后我仍然分别得到 "Societ\xc3\xa0 sportiva Bridge" 和 "Societ\xe0 sportiva Bridge"。

这两个文件都在 CentOS 机器上,并在 UNIX 模式下使用 EOL 转换保存,并将字符集编码设置为 UTF-8(编辑器为 notepad++)。

请试试这个:

$content = file_get_contents('php://input');
$content = mb_convert_encoding($content, 'UTF-8',
          mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));

$theData = json_decode($content, true);

或:

$content = file_get_contents('php://input');
$content = html_entity_decode(mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8"));

$theData = json_decode($content, true);

希望对您有所帮助。