Home > Article > Backend Development > PHP uses json Chinese garbled solution to explain with examples_PHP tutorial
Two commonly used functions in PHP are encode_json() and decode_json();
Let’s focus on the solution to the problem of garbled characters when the encode_json() function is used for Chinese encoding.
First, we write the array we need:
$json = array (
0 =>
array (
id => 13,
name => table tennis,
),
1 =>
array (
id => 17,
name => basketball,
)
)
?>
If we encode directly with encode_json, the output result is:
[{"id":"13","name" :null}
,{"id":"13","name":null}]
?>
Obviously, the Chinese characters are not encoded correctly. This is because json only escapes the encoding,
(assuming that our background file uses gb2312 encoding), so the above statement should convert the encoding first:
foreach ($ajax as $key=>$val)
{
$ajax[$key][name] =
urlencode($val[name]);
}
echo json_encode($json);
?>
In the same way, just decode the encoded Chinese in the client js code with decodeURI().
So far, the problem of Chinese encoding of json in php has been solved.