Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json_encode, json_decode and UTF8

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?

like image 658
Jake Avatar asked Aug 04 '10 18:08

Jake


People also ask

What is the difference between json_encode and json_decode?

I think json_encode makes sure that php can read the . json file but you have to specify a variable name, whereas with json_decode it's the same but you have to specify a file name.

What is json_encode and json_decode in PHP?

JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.

Can JSON handle UTF-8?

JSON may be represented using UTF-8, UTF-16, or UTF-32.

What does json_encode mean?

jsonencode encodes a given value to a string using JSON syntax. The JSON encoding is defined in RFC 7159. This function maps Terraform language values to JSON values in the following way: Terraform type. JSON type.


1 Answers

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!
like image 120
Artefacto Avatar answered Oct 03 '22 08:10

Artefacto