黑帮老公十八岁,切尔西 汉德勒,宝石转转转
本文实例讲述了php 实现 json 数据的编码和解码操作。分享给大家供大家参考,具体如下:
json 使用最频繁的两个操作就是编码和解析数据,php 官方提供了以下 2 个函数实现这两个操作:
编码用于将数据绑定到特定格式。需要此过程来保持数据一致性。解码是一个反向过程,它将编码的数据还原回其原始形式。
使用 json_encode 将 php 的一些数据类型转换为 json 格式,函数包含 3 个参数,分别为:
json_force_object
json_hex_quot
json_hex_tag
json_hex_amp
json_hex_apos
json_invalid_utf8_ignore
json_invalid_utf8_substitute
json_numeric_check
json_partial_output_on_error
json_preserve_zero_fraction
json_pretty_print
json_unescaped_line_terminators
json_unescaped_slashes
json_unescaped_unicode
json_throw_on_error
<?php $input_array = array("zero","one","two"); //returns ["zero","one","two"] $str_json_format = json_encode($input_array); print "json formatted string:" . $str_json_format; //returns {"0":"zero","1":"one","2":"two"} $obj_json_format = json_encode($input_array, json_force_object); print "<br/><br/>json object:" . $obj_json_format; //returns [ "zero", "one", "two" ] $strjsonformat_with_space = json_encode($input_array, json_pretty_print); print "<br/><br/>json formatted string with white space:" . $strjsonformat_with_space;
这是 json encode 的反向操作,用于将 json 编码的数据转换为最初编码的 php数据类型。
json_decode 函数包含 4 个参数,分别为:
true
时,将返回 而非 json_bigint_as_string
, json_invalid_utf8_ignore
, json_invalid_utf8_substitute
, json_object_as_array
, json_throw_on_error
返回值:
返回值为 true
, false
和 null
。
如果 json
无法被解码, 或者编码数据深度超过了递归限制的话,将会返回null
<?php $str_json_array_decoded = json_decode($str_json_format); print "<br/><br/>resultant decoded array from json array:<br/>"; print "<pre>"; print_r($str_json_array_decoded); print "</pre>"; $str_objjson_decoded = json_decode($obj_json_format); print "<br/><br/>resultant decoded object data from json object:<br/>"; print "<pre>"; print_r($str_objjson_decoded); print "</pre>"; $str_jsonary_decoded = json_decode($obj_json_format,true); print "<br/><br/>resultant decoded array data from json object:<br/>"; print "<pre>"; print_r($str_jsonary_decoded); print "</pre>";
stripslashes
对字符串进行处理后,再使用 json_decode 解析如果需要解码的 json 数据中包含有反斜杠 "\",应该使用如下代码进行解码:
$obj = \json_decode(stripslashes($json));
ps:这里再为大家推荐几款比较实用的json在线工具供大家参考使用:
在线json代码检验、检验、美化、格式化工具:
json在线格式化工具:
在线xml/json互相转换工具:
json代码在线格式化/美化/压缩/编辑/转换工具:
c语言风格/html/css/json代码格式化美化工具:
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
php的instanceof和判断闭包Closure操作示例
php数组函数array_push()、array_pop()及array_shift()简单用法示例
yii2.0框架实现上传excel文件后导入到数据库的方法示例
php使用goto实现自动重启swoole、reactphp、workerman服务的代码
网友评论