Json_encode, json_decode and UTF8

空扰寡人 提交于 2019-12-10 20:58:40

问题


All,

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));

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));

to the server, it fails.

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));

How can I modify it such that I pass the exact value as to what I receieved from the json response from the server?


回答1:


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 data already comes encoded in UTF-8. You shouldn't convert it to UTF-8 again; you'll corrupt the data.

Instead of this:

$response = json_decode(utf8_encode($jsonresponse));

You should have this:

$response = json_decode($jsonresponse); //already UTF-8!



回答2:


Set This into your php connection :

$sql = “SET NAMES ‘utf8′”;
mysql_query($sql, $link);



回答3:


have you tryed switching the places of the functions?

$jsonrequest = utf8_encode(json_encode($request));

utf8_encode only encodes strings not arrays




回答4:


You convert the initial request to UTF-8, so I assume it's something else. But when you send the data back, you do not convert it back to the original encoding.

Are you sure you send the data in the encoding expected by the server?




回答5:


I also use both ZF and utf-8 encoded strings in AJAX calls and I think that the uft8_encode and utf8_decode functions should be obsolete.

Do you have a valid meta tag

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" / >

and a valid doctype

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

?



来源:https://stackoverflow.com/questions/3408354/json-encode-json-decode-and-utf8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!