<!-- [if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:PunctuationKerning /> <w:DrawingGridVerticalSpacing>7.8 磅</w:DrawingGridVerticalSpacing> <w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery> <w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery> <w:ValidateAgainstSchemas /> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:Compatibility> <w:SpaceForUL /> <w:BalanceSingleByteDoubleByteWidth /> <w:DoNotLeaveBackslashAlone /> <w:ULTrailSpace /> <w:DoNotExpandShiftReturn /> <w:AdjustLineHeightInTable /> <w:BreakWrappedTables /> <w:SnapToGridInCell /> <w:WrapTextWithPunct /> <w:UseAsianBreakRules /> <w:DontGrowAutofit /> <w:UseFELayout /> </w:Compatibility> <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel> </w:WordDocument> </xml><![endif]--><!-- [if gte mso 9]><xml> <w:LatentStyles DefLockedState="false" LatentStyleCount="156"> </w:LatentStyles> </xml><![endif]--><!-- [if gte mso 10]> <mce:style><! /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} --> <!--[endif] --><!-- [if gte mso 9]><xml> <o:shapedefaults v:ext="edit" spidmax="1026" /> </xml><![endif]--><!-- [if gte mso 9]><xml> <o:shapelayout v:ext="edit"> <o:idmap v:ext="edit" data="1" /> </o:shapelayout></xml><![endif]-->
Json’ 是一种数据交互格式之一,客户端和服务端之间的数据交互,
Json 是 js 的 js 的子集, js 可以很好的解析这种数据格式
Php 对 json 的解析主要是基于两个函数: json-encode 和 json_decode
一、json_encode()
有点像mysql 里面的序列化函数,serialize
该函数主要用来将数组和对象,转换为json 格式。先看一个数组转换的例子:
1. $arr=array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
2.echojson_encode($arr);
结果为1.{"a":1,"b":2,"c":3,"d":4,"e":5}
再看一个对象转换的例子:
1.$obj->body='anotherpost';
2. $obj->id=21;
3. $obj->approved=true;
4. $obj->favorite_count=1;
5.$obj->status=NULL;
6. echojson_encode($obj);
结果
1.{
2."body":"anotherpost",
3."id":21,
4. "approved":true,
5. "favorite_count":1,
6. "status":null
7.}
由于json 只接受utf-8 编码的字符,所以json_encode() 的参数必须是utf-8 编码,否则会得到空字符或者null 。当中文使用GB2312 编码,
或者外文使用ISO-8859-1 编码的时候,这一点要特别注意。
四、json_decode()
类似与反序列化函数
该函数用于将json 文本转换为相应的PHP 数据结构。下面是一个例子:
通常情况下,json_decode() 总是返回一个PHP 对象,而不是数组。比如:
1. $json='{"a":1,"b":2,"c":3,"d":4,"e":5}';
2 var_dump(json_decode($json));
结果就是生成一个PHP 对象:
1.object(stdClass)#1(5){
2. ["a"]=>int(1)
3.["b"]=>int(2)
4. ["c"]=>int(3)
5. ["d"]=>int(4)
6.["e"]=>int(5)
7. }
如果想要强制生成PHP关联数组,json_decode()需要加一个参数true:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json),true);
结果就生成了一个关联数组:
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)}