为什么 php 将某些字符转换为“?”

Why is php converting certain characters to '?'

我代码中的所有内容都是 运行 我的数据库 (Postgresql) 使用的是 utf8 编码,我已经检查了 php.ini 文件,它的编码是 utf8,我尝试调试以查看它是否有任何问题我使用的函数中的一部分是这样做的,但没有什么是预期的 运行,但是在我的前端通过 curl 向后端服务器发送 post 请求以将一些文本插入数据库后,一些'da' 之类的字符会转换为“?”在 postgre 和 memcached 中,我认为 php 出于某种原因在请求到达另一端后再次将它们转换为 Latin-1 因为我在请求之前使用 utf8_encode 并且 utf8_decode 另一边

 this is the code to send the request
         $pre_opp-> 
    
   Send_Request_To_BackEnd("/Settings",$school_name,$uuid,"Upload_Bio","POST",str_replace(" ","%",utf8_encode($bio)));

后端系统是这样接收的

  $data= str_replace("%"," ",utf8_decode($_POST["Data"])); 

不要用“%”替换“”。

使用 urlencode and urldecode 而不是 utf8_encodeutf8_decode - 它将为您提供任何字符的清晰字母数字表示,以便轻松传输数据。

如果您环境中的所有内容都默认为 UTF-8,我想您无论如何都不需要 utf_encodeutf_decode。但如果你仍然这样做,你可以尝试像这样结合两者:

Send_Request_To_BackEnd("/Settings",$school_name,$uuid,"Upload_Bio","POST", urlencode(utf8_encode($bio)));

$data= str_replace("%"," ",utf8_decode(urldecode($_POST["Data"]))); 

你说的像个谜一样:

I think php is converting them to Latin-1 again after the request reaches the other side for some reason

但你自己给出原因:

because I use utf8_encode before the request and utf8_decode on the other side

这正是 uf8_decode 所做的:它将 UTF-8 转换为 Latin-1。

作为the manual explains,这也是您的'?'替换来自:

This function converts the string string from the UTF-8 encoding to ISO-8859-1. Bytes in the string which are not valid UTF-8, and UTF-8 characters which do not exist in ISO-8859-1 (that is, characters above U+00FF) are replaced with ?.

由于您不幸选择了 % 替换 space,像“%da”这样的序列被解释为 URL% 转义,并生成无效的 UTF-8 字符串。然后您要求 PHP 将它们转换为 Latin-1,但它不能,因此它替换为“?”。

简单的解决办法是:不要那样做。如果您的数据已经是 UTF-8 格式,那么这些函数都不会做任何事情,只会把它弄乱;如果它 not 已经在 UTF-8 中,那么找出它的编码并使用 iconv or mb_convert_encoding to convert it, once. See also "UTF-8 all the way through".

由于我们看不到您的 Send_Request_To_BackEnd 功能,因此很难知道您认为自己需要它的原因。如果你用那个字符串构造一个 URL ,你应该在你的请求发送代码中使用 urlencode ;您不需要在另一端对其进行解码,PHP 会为您完成。