JSON in PHP

Source: Internet
Author: User
Tags json urlencode

1.json_encode () Chinese returned as null in gbk/gb2312

The code is as follows

$arr = Array (

Array (

' CatID ' => ' 4 ',

' CatName ' => ' www.111cn.net ',

' Meta_title ' => ' A tutorial Network 2 '

)
);

echo Json_encode ($arr);

Results

[{"CatID": "4", "CatName": "Www.111cn.net", "Meta_title": null}]

Have a look at it? "Meta_title": null he would have been a value for a tutorial network 2, this we checked the principle is json_encode only support uft-8 encoding, we convert

The code is as follows
<?php
$data = "JSON Chinese";
$newData =iconv ("Gb2312″, Utf-8//ignore", $data);
Echo $newData;
Ignore means ignoring the conversion error, and if there is no ignore argument, all characters after that character will not be saved.
or ("Gb2312″," Utf-8″, $data);
?>

Step2

The Background PHP page (page encoding is UTF-8 or has converted the characters to UTF-8) uses Json_encode to convert the array arrays in PHP into JSON strings. For example:

The code is as follows
<?php
$testJSON =array (' name ' => ' Chinese string ', ' value ' => ' test ');
echo Json_encode ($testJSON);
?>
View the output as:
{' name ': ' U4e2du6587u5b57u7b26u4e32″, ' value ': ' Test '}

Visible is the use of UTF8 encoded characters, the use of Json_encode also appeared in Chinese garbled. The solution is to use the Json_encode before using the function UrlEncode (), and then Json_encode, the output of the results in the function UrlDecode () back. as follows:

The code is as follows

<?php
$testJSON =array (' name ' => ' Chinese string ', ' value ' => ' test ');
echo Json_encode ($testJSON);
foreach ($testJSON as $key => $value) {
$testJSON [$key] = UrlEncode ($value);
}
Echo UrlDecode (Json_encode ($testJSON));
?>

View the output as:

{' name ': ' Chinese string ', ' value ': ' Test '}

Summary: Json_encode function can only handle UFT8 string, if it is in Chinese is not good for byte processing, because the Chinese GBK and uft length is not the same oh, this I do not in-depth introduction.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.