PHP Json_decode () and Json_encode () usage and Chinese do not display the workaround _php tutorial

Source: Internet
Author: User
This article describes the Json_decode () and Json_encode () usage in PHP and the Chinese do not display the solution, the need for friends can refer to the next.

PHP Json_decode () and Json_encode ()

1.json_decode ()

Json_decode
(PHP 5 >= 5.2.0, PECL json >= 1.2.0)

json_decode-encoding a JSON-formatted string

Description
Mixed Json_decode (String $json [, bool $assoc])
Accept a JSON-formatted string and convert it to a PHP variable

Parameters

Json
String in JSON string format to decode.

Assoc
When this argument is TRUE, an array is returned instead of an object.


return value
Returns an object or if the optional assoc parameter are TRUE, an associative array is instead returned.

Example

Examples of Example #1 Json_decode ()

The code is as follows Copy Code

$json = ' {' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4, ' E ': 5} ';
Var_dump (Json_decode ($json));
Var_dump (Json_decode ($json, true));
?>

The example above will output:

Object (StdClass) #1 (5) {
["a"] = Int (1)
["B"] = + int (2)
["C"] = + int (3)
["D"] = + int (4)
["e"] = + int (5)
}

Array (5) {
["a"] = Int (1)
["B"] = + int (2)
["C"] = + int (3)
["D"] = + int (4)
["e"] = + int (5)
}


$data = ' [{' name ': ' A1 ', ' Number ': ' 123 ', ' Contno ': ', ' ' qqno ': '},{' Name ': ' A1 ', ' Number ': ' 123 ', ' Contno ': ' $ ', ' qqno ":" "},{" Name ":" A1 "," Number ":" 123 "," Contno ":" The "," Qqno ":"}] ';
echo Json_decode ($data);

The result is:

Array ([0] = StdClass Object ([Name] = + a1 [number] = 123 [Contno] [qqno] = =) [1] = Stdclas s Object ([name] = + a1 [number] = 123 [Contno] [qqno] = = [2] = = StdClass Object ([name] = a 1 [number] [123] [Contno] [qqno] [] =]

It can be seen that the object is compiled by Json_decode (), and now output Json_decode ($data, true) try

The code is as follows Copy Code

Echo Json_decode ($data, true);

Results:

Array ([0] = = Array ([name] = + a1 [number] = 123 [Contno] [qqno] = = [1] = = Array ([name] =& Gt a1 [NUMBER] = 123 [Contno] [qqno] = [2] = = Array ([Name] + a1 [number] = 123 [Contno] => ; [qqno] =))

You can see an associative array of Json_decode ($data, true) output, so Json_decode ($data) outputs an object, and Json_decode ("$arr", true) is forcing it to generate a PHP associative array.

2.json_encode ()

Json_encode
(PHP 5 >= 5.2.0, PECL json >= 1.2.0)

json_encode-JSON Encoding of variables

Report a bug description
String Json_encode (mixed $value [, int $options = 0])
Returns the JSON form of value values

Report a bug parameter

Value
The value to encode, in addition to the resource type, can be any data type

This function can only accept UTF-8 encoded data.

Options
A binary mask consisting of the following constants: Json_hex_quot, Json_hex_tag, Json_hex_amp, Json_hex_apos, Json_numeric_check, Json_pretty_print, JSON_ Unescaped_slashes, Json_force_object, Json_unescaped_unicode.

Report a bug return value
A successful encoding returns a string in JSON form or FALSE on failure.

Report a Bug update log
Release Notes
5.4.0 Options parameter Add constants: Json_pretty_print, Json_unescaped_slashes, and Json_unescaped_unicode.
5.3.3 Options parameter Add constant: Json_numeric_check.
5.3.0 add options parameter.


Report a bug Example

Example #1 a json_encode () example

The code is as follows Copy Code

$arr = Array (' A ' =>1, ' B ' =>2, ' C ' =>3, ' d ' =>4, ' e ' =>5);

echo Json_encode ($arr);
?>

The above routines will output:

{"A": 1, "B": 2, "C": 3, "D": 4, "E": 5}

Example #2 The use of the options parameter in the Json_encode () function

$a = Array (' ' , ' ' Bar ', ' ' Baz ', ' &blong& ', ' xc3xa9 ');

echo "Normal:", Json_encode ($a), "n";
echo "Tags:", Json_encode ($a, Json_hex_tag), "n";
echo "Apos:", Json_encode ($a, Json_hex_apos), "n";
echo "Quot:", Json_encode ($a, Json_hex_quot), "n";
echo "AMP:", Json_encode ($a, json_hex_amp), "n";
echo "Unicode:", Json_encode ($a, Json_unescaped_unicode), "n";
echo "All:", Json_encode ($a, Json_hex_tag | Json_hex_apos | Json_hex_quot | Json_hex_amp | Json_unescaped_unicode), "NN";

$b = Array ();

echo "Empty array output as array:", Json_encode ($b), "n";
echo "Empty array output As Object:", Json_encode ($b, Json_force_object), "NN";

$c = Array (array (all));

echo "non-associative array output as array:", Json_encode ($c), "n";
echo "non-associative array output As Object:", Json_encode ($c, Json_force_object), "NN";

$d = Array (' foo ' = ' bar ', ' baz ' = ' long ');

echo "Associative array always output as object:", Json_encode ($d), "n";
echo "Associative array always output as object:", Json_encode ($d, Json_force_object), "NN";
?>

The above routines will output:

Normal: [" ", "' Bar '", "" "Baz" "," &blong& "," U00e9 "]
Tags: ["u003cfoou003e", "' Bar '," "Baz" "," &blong& "," U00e9 "]
Apos: [" ", "u0027baru0027", "" Baz "", "&blong&", "U00e9"]
Quot: [" ", "' Bar '", "u0022bazu0022", "&blong&", "U00e9"]
AMP: [" ", "' Bar '", "" "Baz" "," u0026blongu0026 "," U00e9 "]
Unicode: [" ", "' Bar '", "" "Baz" "," &blong& "," é "]
All: ["u003cfoou003e", "u0027baru0027", "u0022bazu0022", "u0026blongu0026", "é"]

Empty array Output as array: []
Empty array Output As object: {}

Non-associative array Output as array: [[[+]]
Non-associative array Output As object: {"0": {"0": 1, "1": 2, "2": 3}}

Associative array always output as object: {"foo": "Bar", "baz": "Long"}
Associative array always output as object: {"foo": "Bar", "baz": "Long"}

Example #3 continuous and discontinuous arrays example

copy code

"!--? php
echo "continuous array". Php_eol;
$sequential = Array ("foo", "Bar", "Baz", "Blong");
Var_dump (
$sequential,
Json_encode ($sequential)
);

Echo Php_eol. Non-contiguous array ". Php_eol;
$nonsequential = Array (1=> "foo", 2=> "bar", 3=> "Baz", 4=> "Blong");
Var_dump (
$nonsequential,
Json_encode ($nonsequential)
);

Echo Php_eol. Deletes a contiguous array of values in a way that produces a non-contiguous array ". Php_eol;
Unset ($sequential [1]);
Var_dump (
$sequential,
Json_encode ($sequential)
);
?

The above routines will output:

The code is as follows Copy Code
< p> continuous Array
Array (4) {
[0]=>
String (3) "foo"
[1]=>
String (3) "Bar"
[2]=>
String (3) "Baz" Br>[3]=>
String (5) "Blong"
}
String "[" foo "," Bar "," Baz "," Blong "]"

Non-contiguous array
Array (4) {
[1 ]=>
String (3) "foo"
[2]=>
String (3) "Bar"
[3]=>
String (3) "Baz"
[4]=>
String (5) " Blong "
}
String" {"1": "foo", "2": "Bar", "3": "Baz", "4": "Blong"} "

Delete a contiguous array of values resulting from the non-contiguous array
Array (3) {
[0]=>
String (3) "foo"
[2]=>
String (3) "Baz"
[3]=>
String (5) "Blong"
}
String (33 "{" 0 ":" foo "," 2 ":" Baz "," 3 ":" Blong "}"


$obj->name= ' A1 '; $obj->number = ' 123 ';
$obj->contno= ' 000 ';
Echo Json_encode ($obj);

The

result is:

{"Name": "A1",
"number": "123",
"Contno": "$"
}

As you can see, Json_encode () and Json_decode () are compiled and deserialized, and note that JSON only accepts UTF-8 encoded characters, so the parameters of Json_encode () must be utf-8 encoded, otherwise they will either get null characters or NULL


If it's Chinese, you should pay attention.

Find a workaround on the Web:

The code is as follows Copy Code

/* Handling Json_encode Chinese garbled */
$data = Array (' Game ' = ' ice Fire country ', ' name ' = ' thorn spirit ', ' country ' + ' frost State ', ' level ' = 45);
echo Json_encode ($data);
echo "
";
$newData = Array ();
foreach ($data as $key = = $value) {
$newData [$key] = UrlEncode ($value);
}
Echo UrlDecode (Json_encode ($newData));
?>

Later consulted others, but also can use Base64 code, but base64 code can not put in the URL, Baidu is such explanation:

The standard Base64 is not intended to be transmitted directly in the URL because the URL encoder will change the "/" and "+" characters in the standard Base64 into forms such as "%XX", and these "%" numbers need to be converted when they are deposited into the database because ANSI SQL has used the "%" number as a wildcard character.

But my data is sent via post, not in the head of HTTP, but in Message-body, so it's not affected.

Json_encode can only accept data in utf-8 format


For example: ' Xu ' has been json_encode processed and changed to ' U80e5 ', and the Chinese part of the final JSON is replaced with Unicode encoding. All we have to do is convert the object to JSON and make sure that the Chinese inside the object still appears in the normal Chinese language in JSON, and now it seems that the use of json_encode is not a good idea.
My workaround: First of the class in the text snippet URL encoding (urlencode), and then the object is JSON encoded (Jsonencode), the last URL decoding (urldecode) JSON, that is, the final JSON, the Chinese is still the Chinese!
The test code is as follows:

The code is as follows Copy Code

Class MyClass {
Public $item 1 = 1;
Public $item 2 = ' Chinese ';
function To_json () {
URL encoding to prevent Json_encode from converting Chinese to Unicode
$this->item2 = UrlEncode ($this->item2);
$str _json = Json_encode ($this);
URL decoding, returning each property after the JSON is finished, ensuring that the object properties are not changed
$this->item2 = UrlDecode ($this->item2);
Return UrlDecode ($str _json);
}
}
$c = new MyClass ();
echo Json_encode ($c);
Echo '
';
echo $c->to_json ();
Echo '
';
echo Json_encode ($c);
Echo '
';
Echo json_encode (' Xu ');
?>

Program Output Result:

{"Item1": 1, "item2": "u4e2du6587"}
{"Item1": 1, "item2": "Chinese"}
{"Item1": 1, "item2": "u4e2du6587"}
"U80e5"


http://www.bkjia.com/PHPjc/632210.html www.bkjia.com true http://www.bkjia.com/PHPjc/632210.html techarticle This article describes the Json_decode () and Json_encode () usage in PHP and the Chinese do not display the solution, the need for friends can refer to the next. PHP Json_decode () and Json_encode () 1.js ...

  • 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.