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

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

本文关键字:来自 AJAX POST 调用 意外 解码 PHP 字符串      更新时间:2023-09-26

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

使用"常用"字符时一切都很好,但当使用带有"à"等重音的元音时,我会发现不一致。我想问是否有人对如何解决这个问题有建议。

这是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在解码之前,我得到了"Societ''xe0 sportiva Bridge"。

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

我还尝试使用encodeURIComponent()或escape()对字符串客户端进行编码。PHP接收到正确的字符串(分别为"Societ%C3%A0%20Sportriva%20Bridge"answers"Societ%E0%20sportiva%20Bridge"),但在用rawurldecode()解码后,我仍然分别得到"Societ''xc3''xa0-sportriva Bridge"answers"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);

我希望这对你有帮助。