Solve the json_encode of PHP to deal with Chinese transcoding as a whole English method

Source: Internet
Author: User
Tags pack urlencode


The recent use of Json_encode transform arrays into JSON data, stored in the database, because the length of the field is not determined, you can only use this method, but the use of json_decode resolution of the array, there is a class


Like "U590fu5a03u7684u8bf1u60d14u5979u7684u6280u5de7″, through the query Baidu, this should be a UCS-2 encoded string, then how to convert this string?"

In fact, in the previous version of php5.2 to do json_encode conversion time. Chinese will be UNICODE encoding, php5.3 added the options parameter, after 5.4 to join the Json_unescaped_unicode, this parameter, do not need to do escape and UNICODE processing. So it is necessary to deal with Chinese before 5.4.
php5.4 inside the deal

Json_encode ($str, Json_unescaped_unicode);

Before php5.4, there are two ways of handling

Method One

function Encode_json ($str) {return
preg_replace ("/U (0-9a-f]+)/ie", Iconv (' UCS-2 ', ' UTF-8 ', pack (' H4 ', ' \  1 ')) ", $code);
}

In practical applications there is a problem, some of the characters will be dropped, not only why, such as strings: "Date 11.2″ will be changed to" date. 2″.

Method Two

function Encode_json ($str) {return
UrlDecode (Json_encode (Url_encode ($STR)));
}
function Url_encode ($str) {
if (Is_array ($STR)) {
foreach ($str as $key => $value) {
$s        Tr[urlencode ($key)] = Url_encode ($value);
}
Else {
$str = UrlEncode ($STR);
return
$str;
}


This site is using a virtual host, you can not modify the version of PHP, so you can only use the first method, but the method does still have effect.

Method three
function Decodeunicode ($str) {return
preg_replace_callback ('/\\\\u ([0-9a-f]{4})/I ',
create_   function (
' $matches ',
' Return mb_convert_encoding (Pack ("h*", $matches [1]), "UTF-8", "ucs-2be"); '
),
$str);

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.