PHP原生提供json_encode()和json_decode()函数,前者用于编码、解码json数据。
json_encode()
<?php $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); echo json_encode($arr); // 输出 // {"a":1,"b":2,"c":3,"d":4,"e":5} ?>
$obj->body = 'another post'; $obj->id = 21; $obj->approved = true; $obj->favorite_count = 1; $obj->status = NULL; echo json_encode($obj); // 结果 // { // "body":"another post", // "id":21, // "approved":true, // "favorite_count":1, // "status":null // }
由于json只接受utf-8编码的字符,所以json_encode()的参数必须是utf-8编码,否则会得到空字符或者null。当中文使用GB2312编码,或者外文使用ISO-8859-1编码的时候,这一点要特别注意。
json_decode()
$json = '{"foo": 12345}'; $obj = json_decode($json); print $obj->{'foo'}; // 12345
通常情况下,json_decode()总是返回一个PHP对象,而不是数组。
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json)); // 结果是一个对象 // object(stdClass)#1 (5) { // ["a"] => int(1) // ["b"] => int(2) // ["c"] => int(3) // ["d"] => int(4) // ["e"] => int(5) // }
如果想要强制生成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) // }
© 版权声明
特别声明:该文观点仅代表作者本人,"遇见科技圈"仅提供信息存储空间服务,如需转载、摘编请取得原作者授权。
THE END