The php tutorial comes with json_encode to process json data, so their support for Chinese is not good. Let’s take a look at an example
echo json_encode(array(123213,'China'));
{"platformid":"123213","userid":"1023","username":"u00b7u00f0u00b5u00b2u00c9u00b1u00b7u00f0u00ccu00fc"}
We will find that English can be parsed correctly, but Chinese comes out as u00b7u00f0u00b5u00b2u00c9u00b1u00b7u00f0u00ccu00fc. Oh, this may be unicode encoding, but I haven't tested it and I just guessed it. Let’s take a look at a function that solves json Chinese garbled characters
private function to_utf8($in)
{
if (is_array($in)) {
foreach ($in as $key => $value)
{
$out[$this->to_utf8($key)] = $this->to_utf8($value);
}
}
elseif(is_string($in))
{
if(mb_detect_encoding()($in) != "utf-8")
return utf8_encode($in);
else
return $in;
}
else
{
return $in;
}
return $out;
}
1. Output $usr->username directly, and set charset=utf-8 in the page header. Garbled characters
2.echo json_encode($usr) output username=null
3. The page header is set to charset=gbk, and the output is correct -> It can be determined that the original encoding is gbk
Finally, the conclusion was drawn through ie, chrome, and firefox tests:
1. Ensure that the character set of the page is consistent with the database tutorial, and the output must be normal.
2. When doing json_encode, ensure that the data encoding is utf-8 and json_decode is normal.
3. If you want to json_encode non-utf-8 characters, convert them to utf-8 first.
4. When doing json_decode for non-utf-8 characters, be sure not to forget to convert them to the original encoding, otherwise garbled characters will be output!!