Function to solve json Chinese garbled code in php_PHP tutorial

WBOY
Release: 2016-07-13 10:54:37
Original
907 people have browsed it

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!!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632302.htmlTechArticlephp tutorial comes with json_encode to process json data, so their support for Chinese is not good, let’s take a look below Examples echo json_encode(array(123213,'China')); {platformid:123213,u...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template