Application of JSON in PHP _ PHP Tutorial

Source: Internet
Author: User
Introduction to the application of JSON in PHP. Starting from version 5.2, PHP provides native json_encode () and json_decode () functions. The former is used for encoding and the latter is used for decoding. 1. json_encode () this function is mainly used to convert arrays and objects from version 5.2. PHP Native provides json_encode () and json_decode () functions, which are used for encoding, the latter is used for decoding.
I. json_encode ()
This function is mainly used to convert arrays and objects to json format. First, let's look at an example of array conversion:
$ Arr = array ('a' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5 );
Echo json_encode ($ arr );
Result:
{"A": 1, "B": 2, "c": 3, "d": 4, "e": 5}
Let's look at an example of object conversion:

The code is as follows:


$ Obj-> body = 'another post ';
$ Obj-> id = 21;
$ Obj-> approved = true;
$ Obj-> favorite_count = 1;
$ Obj-> status = NULL;
Echo json_encode ($ obj );


Result:

The code is as follows:


{
"Body": "another post ",
"Id": 21,
"Approved": true,
"Favorite_count": 1,
"Status": null
}


Because json only accepts UTF-8 encoded characters, the json_encode () parameter must be UTF-8 encoded. otherwise, null or null is obtained. Pay special attention to this when Chinese characters use GB2312 encoding or foreign languages use ISO-8859-1 encoding.

2. index array and associated array

PHP supports two types of arrays: one is to save only the index array (indexed array) of "value", and the other is to save "name/value) associated array (associative array ).
Because javascript does not support associating arrays, json_encode () only converts the index array (indexed array) to the array format, and converts the associated array (associative array) to the object format.
For example, there is an index array

The code is as follows:


$ Arr = Array ('one', 'two', 'Three ');
Echo json_encode ($ arr );


Result:
["One", "two", "three"]
If you change it to an associated array:
$ Arr = Array ('1' => 'one', '2' => 'two', '3' => 'Three ');
Echo json_encode ($ arr );
The result is changed:
{"1": "one", "2": "two", "3": "three "}
Note that the data format is changed from "[]" (array) to "{}" (object ).
If you want to forcibly convert an "index array" to "object", you can write
Json_encode (object) $ arr );
Or
Json_encode ($ arr, JSON_FORCE_OBJECT );

III. class conversion

The following is a PHP class:

The code is as follows:


Class Foo {
Const ERROR_CODE = '000000 ′;
Public $ public_ex = 'This is public ';
Private $ private_ex = 'This is private! ';
Protected $ protected_ex = 'This shocould be protected ';
Public function getErrorCode (){
Return self: ERROR_CODE;
}
}


Now, perform json conversion on the instance of this class:

The code is as follows:


$ Foo = new Foo;
$ Foo_json = json_encode ($ foo );
Echo $ foo_json;


The output result is
{"Public_ex": "this is public "}
As you can see, except the public variable, other things (constants, private variables, methods, and so on) are lost.

IV. json_decode ()

This function is used to convert json text to the corresponding PHP Data structure. The following is an example:

The code is as follows:


$ Json = '{"foo": 12345 }';
$ Obj = json_decode ($ json );
Print $ obj-> {'foo'}; // 12345


In general, json_decode () always returns a PHP object instead of an array. For example:
$ Json = '{"a": 1, "B": 2, "c": 3, "d": 4, "e": 5 }';
Var_dump (json_decode ($ json ));
The result is to generate a PHP object:

The code is as follows:


Object (stdClass) #1 (5 ){
["A"] => int (1)
["B"] => int (2)
["C"] => int (3)
["D"] => int (4)
["E"] => int (5)
}


If you want to forcibly generate a PHP join array, json_decode () requires a parameter true:
$ Json = '{"a": 1, "B": 2, "c": 3, "d": 4, "e": 5 }';
Var_dump (json_decode ($ json), true );
The result generates an associated array:

The code is as follows:


Array (5 ){
["A"] => int (1)
["B"] => int (2)
["C"] => int (3)
["D"] => int (4)
["E"] => int (5)
}



5. common errors of json_decode ()

The three json statements below are all incorrect. can you tell where the error is?

The code is as follows:


$ Bad_json = "{'bar': 'Baz '}";
$ Bad_json = '{bar: "baz "}';
$ Bad_json = '{"bar": "baz ",}';


If json_decode () is executed on these three strings, null is returned and an error is returned.
The first error is that the json separator (delimiter) only allows double quotation marks and does not support single quotation marks. The second error is the "name" of the json name-value pair (the part on the left of the colon). double quotation marks must be used in any case. The third error is that you cannot add a comma (trailing comma) after the last value ).
In addition, json can only be used to represent objects and arrays. if json_decode () is used for a string or value, null is returned.
Var_dump (json_decode ("Hello World"); // null

Encode () and json_decode () functions. The former is used for encoding, and the latter is used for decoding. I. json_encode () this function is mainly used to convert arrays and objects...

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.