Home > Article > Backend Development > Summary of classic cases of php processing json format data, json classic case_PHP tutorial
The examples in this article summarize the method of php processing json format data. Share it with everyone for your reference, the details are as follows:
1.json introduction:
What is json?
Simply put, JSON converts a set of data represented in a JavaScript object into a string, which can then be easily passed between functions, or from a web client in an asynchronous application Passed to the server-side program.
In layman’s terms, it is a data storage format, just like a PHP serialized string.
It is also a kind of data description. For example, if we serialize an array and store it, it can be easily deserialized and applied; the same is true for json, but it is built to interact with client-side javascript and server-side php. bridge.
How to use json?
Since PHP5.2 and later versions have built-in json support, there are two main functions:
json_encode(): Encoding, generate a json string
json_decode(): a decode
Note: After encoding with the json_encode() function, a string in json format will be returned, such as: $json = '{"a":1,"b":2,"c" :3,"d":4,"e":5}';Output the string in json format and you will get a javascript object in json format
2.json Case 1:
Usage of json_encode:
<?php $arr = array( 'name' => '魏艳辉', 'nick' => '为梦翱翔, 'contact' => array( 'email' => 'zhuoweida@163.com', 'website' => 'http://zhuoweida.blog.tianya.cn', ) ); $json_string = json_encode($arr); echo $json_string;//json格式的字符串 ?>
Result:
{ "name":"\u9648\u6bc5\u946b", "nick":"\u6df1\u7a7a", "contact": { "email":"shenkong at qq dot com", "website":"http:\/\/www.chinaz.com" } }
Tips:The output data itself is a js object in json format. Because there are no quotes, it can be used directly as a json object on the front page
Summary: Associative arrays are constructed according to JavaScript objects
Analysis: The above case is a simple jsonization of an array. It should be pointed out that in non-utf-8 encoding, Chinese characters cannot be encoded, and the result will be a null value, so if you use gb2312 encoding to write PHP code, then you need to use iconv or mb series functions to convert the content containing Chinese into utf-8 and then use it in json_encode
3.json case two:
Usage of json_decode:
<?php $arr = array( 'name' => '魏艳辉', 'nick' => '为梦翱翔', 'contact' => array( 'email' => 'zhuoweida@163.com', 'website' => 'http://zhuoweida.blog.tianya.cn', ) ); $json_string = json_encode($arr); $obj = json_decode($json_string); //可以使用$obj->name访问对象的属性 $arr=json_decode($json_string,true);//将第二个参数为true时将转化为数组 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: Associative arrays are constructed according to JavaScript objects
Tips:The output data itself is a js object in json format. Because there are no quotes, it can be used directly as a json object on the front page
Analysis: Decoding is necessary after encoding. PHP provides the corresponding function json_decode. After executing this function, an object or array will be obtained.
4.json case three:
When interacting with the front desk, 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 json format data to a variable, and it becomes a javascript object, so that we can easily traverse obj
Tips: In JavaScript, array access is through index; object attribute access is through object name.property name
Tips:The output data itself is a js object in json format. Because there are no quotes, it can be used directly as a json object on the front page
5.json Case 4: json cross-domain data call:
For example: 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>
For example: called file profile.php
<?php $arr = array( 'name' => '魏艳辉', 'nick' => '为梦翱翔', '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, a json string is generated and passed to getProfile as a parameter, and then the nickname is inserted into the div. In this way, a cross-domain data interaction is completed
6. How does js parse the json string returned by the server?
When we use ajax to interact between the client and the server, on the premise that frameworks such as jQuery are not applicable, the general approach is to have the server return a json string, and then parse it into a javascript object on the client . The method used during parsing is generally eval or new function, and currently ie8 and firefox3.1 have built-in native json objects.
Example 1:
var strTest='{"a":"b"}'; //转换成JS对象 var obj=eval("("+strTest+")") ;
Example 2:
function strtojson(strTest){ JSON.parse(str); }
7. Case 5: jsonization of objects
<?php //1.对象 class JsonTest{ var $id = 1; var $name = 'heiyeluren'; $gender = '男'; } $obj = new JsonTest; echo json_encode($obj)."<br /> "; ?>
Browser output:
{ "id":1, "name":"heiyeluren", "gender":"\u7537" }
Conclusion: The json string of the object is constructed according to the javascript object. Unable to recognize Chinese, all Chinese strings are not displayed correctly
Analysis:The above case is a simple jsonization of an array. It should be pointed out that under non-utf-8 encoding, Chinese characters will not be encoded, and the result will be a null value, so if If you use gb2312 encoding to write PHP code, then you need to use iconv or mb series functions to convert the Chinese content into utf-8 and then use it in json_encode
Tips:The output data itself is a js object in json format. Because there are no quotes, it can be used directly as a json object on the front page
8. Case 6: JSONization of index array
<?php $arr1 = array(1, 'heiyeluren', '男'); echo json_encode($arr1)."<br /> "; ?>
Browser output:
[ 1, "heiyeluren", "\u7537" ]
结论:纯数字索引数组的json字符串是按照javascript能够识别的数组来存储的,而不是按照javascript能够识别的对象来存储的。无法识别中文,所有的中文字符串没有被正确显示出来
分析:上述案例很简单的将一个数组json化了,需要指出的是在非utf-8编码下,中文字符将不可被encode,结果会出来空值,所以如果你使用gb2312编码编写php代码,那么就需要将包含中文的内容使用iconv或mb系列函数转化为utf-8后在json_encode
9.案例七:关联数组的json化
<?php $arr2 = array("id"=>1, "name"=>'heiyeluren', "gender"=>'男'); echo json_encode($arr2)."<br /> "; ?>
浏览器输出结果:
{ "id":1, "name":"heiyeluren", "gender":"\u7537" }
结论:关联索引数组的json字符串是按照javascript对象的形式来构造的。无法识别中文,所有的中文字符串没有被正确显示出来
分析:上述案例很简单的将一个数组json化了,需要指出的是在非utf-8编码下,中文字符将不可被encode,结果会出来空值,所以如果你使用gb2312编码编写php代码,那么就需要将包含中文的内容使用iconv或mb系列函数转化为utf-8后在json_encode
提示:输出的数据本身就是json格式的js对象,因为没有带引号,所以在前台页面可以直接将其当做json对象使用
10.案例八:对多维索引数组的进行json化
<?php $arr3 = array(array(1, 'heiyeluren', '男'), array(1, 'heiyeluren', '男')); echo json_encode($arr3)."<br /> ";?>
浏览器输出结果:
[ [1,"heiyeluren","\u7537"], [1,"heiyeluren","\u7537"] ]
结论:多维数字索引数组的json字符串是按照javascript能够识别的数组来存储的。无法识别中文,所有的中文字符串没有被正确显示出来
分析:上述案例很简单的将一个数组json化了,需要指出的是在非utf-8编码下,中文字符将不可被encode,结果会出来空值,所以如果你使用gb2312编码编写php代码,那么就需要将包含中文的内容使用iconv或mb系列函数转化为utf-8后在json_encode
提示:输出的数据可以直接将其当做javascript数组使用
11.案例九:对多维关联数组的进行json化
<?php $arr4 = array( array("id"=>1, "name"=>'heiyeluren', "gender"=>'男'), array("id"=>1, "name"=>'heiyeluren', "gender"=>'男') ); echo json_encode($arr4)."<br /> "; ?>
浏览器输出结果:
[ {"id":1,"name":"heiyeluren","gender":"\u7537"}, {"id":1,"name":"heiyeluren","gender":"\u7537"} ]
结论:多维关联索引数组是按照外围是JavaScript数组,中间的索引数组是对象。无法识别中文,所有的中文字符串没有被正确显示出来
分析:上述案例很简单的将一个数组json化了,需要指出的是在非utf-8编码下,中文字符将不可被encode,结果会出来空值,所以如果你使用gb2312编码编写php代码,那么就需要将包含中文的内容使用iconv或mb系列函数转化为utf-8后在json_encode
提示:输出的数据可以直接将其当做javascript数组使用
12.案例十:json格式的javascript对象的创建
json的格式与语法:
var jsonobject= { //对象内的属性语法(属性名与属性值是成对出现的) propertyname:value, //对象内的函数语法(函数名与函数内容是成对出现的) functionname:function(){...;} };
注意:
①jsonobject -- JSON对象名称
②propertyname -- 属性名称
③functionname -- 函数名称
④一对大括号,括起多个"名称/值"的集合
⑤属性名或函数名可以是任意字符串,甚至是空字符串
⑥逗号用于隔开每对"名称/值"对
提示:
①在javascript中,数组的访问是通过索引来访问的; 对象属性的访问是通过 对象名.属性名 来访问的
②经过json_encode()化而的数据都是js能够识别的格式,而经过json_decode()化的数据都是php能够识别的格式,这一点大家心里要清楚
③经过json_encode()化而输出的数据都是json格式的javascript对象,在前台可直接将其当做js对象使用
另外,本站还提供了如下格式化与转换工具方便大家使用:
php代码在线格式化美化工具:
http://tools.jb51.net/code/phpformat
在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson
JavaScript代码美化/压缩/格式化/加密工具:
http://tools.jb51.net/code/jscompress
在线XML格式化/压缩工具:
http://tools.jb51.net/code/xmlformat
Readers who are interested in more PHP-related content can check out the special topics of this site: "Summary of JSON format data operation skills in PHP", "Summary of PHP file operations", "Summary of PHP operations and operator usage", "PHP Network Summary of Programming Skills", "Introduction Tutorial on PHP Basic Syntax", "Summary of PHP Office Document Operation Skills (Including Word, Excel, Access, PPT)", "Summary of PHP Date and Time Usage", "Introduction Tutorial on PHP Object-Oriented Programming" , "php string (string) usage summary", "php mysql database operation introductory tutorial" and "php common database operation skills summary"
I hope this article will be helpful to everyone in PHP programming.