What to note in PHP Json_encode functions

Source: Internet
Author: User

Using Json_encode () built-in functions in PHP can be used to better communicate and use data in PHP with other languages.

The function is to convert an array into a JSON data storage format:

1 <?php2     $arr =array (' name ' = ' Balla_ rabbit ', ' age ' =>22); 3     echo Json_encode ($arr); 4?>

Output Result:

1 {"Name": "", "Age": 22}

The Json_encode function in Chinese is encoded as NULL, check the information, very simple, in order to closely integrate with the front end, JSON only support UTF-8 encoding.

We can use the Iconv function to convert the following code:

1 string iconv (String $in _charset, String $out _charset, String $str) 2 performs a character set conversion on the Stri Ng str from In_charset to out_charset.//conversion from In_charset encoding to OUT_CHARSET,STR
1 <?php2     $arr =array (' name ' =>iconv (' GBK ', ' utf-8 ', ' Balla_ Rabbit '), ' age ' =>22); 3     echo Json_encode ($arr) ; 4?>

Output Result:

1 {"Name": "Balla_\u934f\u65bf\u74d9", "Age": 22}

All Chinese in the array are missing after the Json_encode or appear \u934f\u65bf\ and so on.

The solution is to use the UrlEncode () function, and before Json_encode, all the contents of all the arrays are processed with UrlEncode (), and then converted to a JSON string with Json_encode () and then UrlDecode (). Turn the encoded Chinese back.

1 string  UrlEncode (String $str)//urlencode: Returns the string as a URL-encoded return value: string
1 <?php 2      3     $arr =array (' name ' =>urlencode (' Balla_ rabbit '), ' age ' =>22); 4      5     $json =json_encode ($ ARR); 6  7     $result =json_decode ($json, true);//decode JSON and convert to array 8      9     Echo urldecode ($result [' name ']); 10 11? >

Output Result:

1 Balla_ Rabbits

 

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.