Summary of typical cases of php processing json format data, and typical cases of json
This example summarizes how php processes json data. We will share this with you for your reference. The details are as follows:
1. json introduction:
What is json?
Simply put, JSON can convert a set of data represented in a JavaScript object to a string, and then it can be easily passed between functions, alternatively, the string is transmitted from the Web Client to the server in an asynchronous application.
In layman's terms, it is a data storage format, just like a php serialized string.
It is also a data description. For example, if we store an array after serialization, it can be easily deserialized and applied. json is also the case, it builds a bridge between client javascript and server php.
How to Use json?
Versions starting from php5.2 and later have built-in json support, mainly including two functions:
Json_encode (): encoded to generate a json string
Json_decode (): A decoder
Note:After json_encode () function encoding, a json string is returned, for example, $ json = '{"a": 1, "B": 2, "c ": 3, "d": 4, "e": 5} '; output a string in json format and a javascript Object in json format will be obtained.
2. json Case 1:
Use of json_encode:
<? Php $ arr = array ('name' => 'wei Yanhui ', 'Nick' =>, 'Contact '=> array ('email' => 'zhuoweida @ 163.com ', 'website' => 'HTTP: // zhuoweida.blog.tianya.cn ',)); $ json_string = json_encode ($ arr); echo $ json_string; // string in json format?>
Result:
{ "name":"\u9648\u6bc5\u946b", "nick":"\u6df1\u7a7a", "contact": { "email":"shenkong at qq dot com", "website":"http:\/\/www.chinaz.com" }}
Tip:The output data itself is a js object in json format. Because there is no quotation mark, you can directly use it as a json object on the front-end page.
Summary:The Correlated array is constructed according to the javascript Object.
Analysis: in the above case, an array is converted into json. It should be noted that in non-UTF-8 encoding, Chinese characters cannot be encoded and the result will be null, therefore, if you use gb2312 encoding to write php code, you need to convert the content that contains Chinese characters into UTF-8 using iconv or mb functions
3. json Case 2:
Use of json_decode:
<? Php $ arr = array ('name' => 'wei Yanhui ', 'Nick' => 'dream soar ', 'Contact '=> array ('email' => 'zhuoweida @ 163.com ', 'website' => 'HTTP: // zhuoweida.blog.tianya.cn ',)); $ json_string = json_encode ($ arr); $ obj = json_decode ($ json_string); // you can use $ obj-> name to access the attributes of the object $ arr = json_decode ($ json_string, true); // when the second parameter is set to true, it will be converted to the array print_r ($ obj); print_r ($ arr);?>
Result:
{ "name":"\u9648\u6bc5\u946b", "nick":"\u6df1\u7a7a", "contact": { "email":"shenkong at qq dot com", "website":"http:\/\/www.chinaz.com" }}
Summary:The Correlated array is constructed according to the JavaScript Object.
Tip:The output data itself is a js object in json format. Because there is no quotation mark, you can directly use it as a json object on the front-end page.
Analysis:Decoding is required after encoding. php provides the corresponding function json_decode. After executing this function, an object or array will be obtained.
4. json Case 3:
When interacting with the foreground, the role of json is displayed:
For example, the javascript code is as follows:
<script type="text/javascript">var obj = { "name":"\u9648\u6bc5\u946b", "nick":"\u6df1\u7a7a", "contact": { "email":"shenkong at qq dot com", "website":"http:\/\/www.chinaz.com" } }; alert(obj.name);</script>
Code analysis: the above Code directly assigns the json format data to a variable, which becomes a javascript Object, so that we can easily traverse obj.
Tip:In javascript, arrays are accessed through indexes. Object Attributes are accessed by object names. Attribute names.
Tip:The output data itself is a js object in json format. Because there is no quotation mark, you can directly use it as a json object on the front-end page.
5. json case 4: json cross-Origin data calling:
For example, the main file index.html
<script type="text/javascript"> function getProfile(str) { var arr = str; document.getElementById('nick').innerHTML = arr.nick; }</script><body> <div id="nick"></div></body><script type="text/javascript" src="http://localhost/demo/profile.php"></script>
Example: profile. php file called
<? Php $ arr = array ('name' => 'wei Yanhui ', 'Nick' => 'dream soar ', 'Contact '=> array ('email' => 'zhuoweida @ 163.com ', 'website' => 'HTTP: // zhuoweida.blog.tianya.cn ',)); $ json_string = json_encode ($ arr); echo "getProfile ($ json_string)";?>
Code Analysis:When index.html calls profile. php, The json string is generated, and the getProfile is passed as a parameter. Then, the nickname is inserted into the div, so that a cross-Origin data interaction is completed.
6. How does js parse the json string returned by the server?
When using ajax for client-side interaction with the server, the general practice is to let the server return a json string without applying jQuery and other frameworks, then parse it into a javascript object on the client. The method used for parsing is generally eval or new function, while ie8 and firefox3.1 currently have built-in native json objects.
Example 1:
Var strTest = '{"a": "B"}'; // convert to the JS object var obj = eval ("(" + strTest + ")");
Example 2:
function strtojson(strTest){ JSON.parse(str);}
7. Case 5: json object
<? Php // 1. object class JsonTest {var $ id = 1; var $ name = 'heiyeluren'; $ gender = 'male';} $ obj = new JsonTest; echo json_encode ($ obj ). "<br/>";?>
Browser output result:
{ "id":1, "name":"heiyeluren", "gender":"\u7537"}
Conclusion:The json string of the object is constructed according to the javascript Object. Chinese cannot be recognized, and all Chinese strings are not correctly displayed
Analysis:In the above case, an array is converted into json. It should be noted that in non-UTF-8 encoding, Chinese characters cannot be encoded and the result will be null, therefore, if you use gb2312 encoding to write php code, you need to convert the content that contains Chinese characters into UTF-8 using iconv or mb functions
Tip:The output data itself is a js object in json format. Because there is no quotation mark, you can directly use it as a json object on the front-end page.
8. Case 6: json-based index array
<? Php $ arr1 = array (1, 'heiyeluren', 'mal'); echo json_encode ($ arr1). "<br/>";?>
Browser output result:
[ 1, "heiyeluren", "\u7537"]
Conclusion:The json string of a pure numeric index array is stored based on an array that can be identified by javascript, rather than an object that can be identified by javascript. Chinese cannot be recognized, and all Chinese strings are not correctly displayed
Analysis:In the above case, an array is converted into json. It should be noted that in non-UTF-8 encoding, Chinese characters cannot be encoded and the result will be null, therefore, if you use gb2312 encoding to write php code, you need to convert the content that contains Chinese characters into UTF-8 using iconv or mb functions
9. Case 7: json-based association Array
<? Php $ arr2 = array ("id" => 1, "name" => 'heiyeluren', "gender" => 'male'); echo json_encode ($ arr2 ). "<br/>";?>
Browser output result:
{ "id":1, "name":"heiyeluren", "gender":"\u7537"}
Conclusion:Json strings associated with the index array are constructed in the form of javascript objects. Chinese cannot be recognized, and all Chinese strings are not correctly displayed
Analysis:In the above case, an array is converted into json. It should be noted that in non-UTF-8 encoding, Chinese characters cannot be encoded and the result will be null, therefore, if you use gb2312 encoding to write php code, you need to convert the content that contains Chinese characters into UTF-8 using iconv or mb functions
Tip:The output data itself is a js object in json format. Because there is no quotation mark, you can directly use it as a json object on the front-end page.
10. Case 8: json-based multi-dimensional Index Array
<? Php $ arr3 = array (1, 'heiyeluren', 'male'), array (1, 'heiyeluren', 'male'); echo json_encode ($ arr3 ). "<br/>";?>
Browser output result:
[ [1,"heiyeluren","\u7537"], [1,"heiyeluren","\u7537"]]
Conclusion:Json strings of multidimensional numeric index arrays are stored in arrays that can be identified by javascript. Chinese cannot be recognized, and all Chinese strings are not correctly displayed
Analysis:In the above case, an array is converted into json. It should be noted that in non-UTF-8 encoding, Chinese characters cannot be encoded and the result will be null, therefore, if you use gb2312 encoding to write php code, you need to convert the content that contains Chinese characters into UTF-8 using iconv or mb functions
Tip:The output data can be directly used as a javascript array.
11. Case 9: json-based multi-dimensional joined Arrays
<? Php $ arr4 = array ("id" => 1, "name" => 'heiyeluren', "gender" => 'male '), array ("id" => 1, "name" => 'heiyeluren', "gender" => 'male'); echo json_encode ($ arr4 ). "<br/>";?>
Browser output result:
[ {"id":1,"name":"heiyeluren","gender":"\u7537"}, {"id":1,"name":"heiyeluren","gender":"\u7537"}]
Conclusion:The multidimensional associated index array is a JavaScript Array Based on the periphery, and the index array in the middle is an object. Chinese cannot be recognized, and all Chinese strings are not correctly displayed
Analysis:In the above case, an array is converted into json. It should be noted that in non-UTF-8 encoding, Chinese characters cannot be encoded and the result will be null, therefore, if you use gb2312 encoding to write php code, you need to convert the content that contains Chinese characters into UTF-8 using iconv or mb functions
Tip:The output data can be directly used as a javascript array.
12. Case 10: Create a javascript Object in json format
Json format and Syntax:
Var jsonobject = {// attribute syntax in the object (Attribute names and attribute values appear in pairs) propertyname: value, // function syntax in the object (function names and function content appear in pairs) functionname: function (){...;}};
Note:
① Jsonobject -- JSON Object Name
② Propertyname -- attribute name
③ Functionname -- function name
④ A pair of braces, including multiple "name/value" sets
⑤ The attribute name or function name can be any string or even a Null String
⑥ Use commas to separate each pair of "name/value" Pairs
Tip:
① In javascript, access to arrays is accessed through indexes; Access to object attributes is accessed through object name. attribute name.
② After json_encode (), the data is in a format that can be recognized by js, and the data that passes through json_decode () is in a format that can be recognized by php. This is clear to everyone.
③ After json_encode (), the output data is javascript objects in json format. It can be directly used as a js object in the foreground.
In addition,This site also provides the following formatting and conversion tools for your convenience:
Php code online formatting and beautification tools:
Http://tools.jb51.net/code/phpformat
Online XML/JSON conversion tools:
Http://tools.jb51.net/code/xmljson
JavaScript code beautification/compression/formatting/encryption tools:
Http://tools.jb51.net/code/jscompress
Online XML formatting/compression tools:
Http://tools.jb51.net/code/xmlformat