Json_encode,json_decode和UTF8 [英] Json_encode, json_decode and UTF8
问题描述
全部
我使用PHP向Web服务器发出JSON请求,它在变量中返回了JSON响应. JSON响应将包含许多键和值.我从服务器获得的JSON响应中包含特殊字符.因此,我使用以下语句将其转换为UTF8,对JSON进行解码,并将其用作显示到UI的数组.
I make a JSON request to a web server using PHP and it returns me a JSON response in a variable. The JSON response will have lots of keys and values. The JSON response I get from the server has special characters in it. So, I use the following statement to convert it to UTF8,decode the JSON and use it as an array to display to the UI.
$response = json_decode(utf8_encode($jsonresponse));
现在,我必须在JSON请求中将相同的值传递给服务器以执行某些操作.但是,当我通过
Now, I have to pass the same value to the server in a JSON request to do some stuff. However, when I pass
$jsonrequest = json_encode(utf8_encode($request));
到服务器,它失败.
以下代码成功读取特殊字符并将其显示在UI中.但是如果我必须将utf8_encode值传递到服务器,则会失败.
The following code succeeds in reading special characters and displaying it to the UI. But fails if I have to pass the utf8_encode value to the server.
当前的整个往返代码如下:
The current whole roundtrip code is as under:
$requestdata = json_encode($request);
$jsonresponse = //Do something to get from server;
$response = json_decode(utf8_encode($jsonresponse));
如何修改它,以便我传递服务器接收到的来自json响应的确切值?
How can I modify it such that I pass the exact value as to what I receieved from the json response from the server?
推荐答案
我从服务器获得的JSON响应中包含特殊字符.因此,我使用以下语句将其转换为UTF8,对JSON进行解码,并将其用作显示到UI的数组.
The JSON response I get from the server has special characters in it. So, I use the following statement to convert it to UTF8,decode the JSON and use it as an array to display to the UI.
JSON数据已经以UTF-8编码.您不应该再次将其转换为UTF-8.您将破坏数据.
JSON data already comes encoded in UTF-8. You shouldn't convert it to UTF-8 again; you'll corrupt the data.
代替此:
$response = json_decode(utf8_encode($jsonresponse));
您应该有这个:
$response = json_decode($jsonresponse); //already UTF-8!
这篇关于Json_encode,json_decode和UTF8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!