在php中,可以使用json_encode()函数将字符串变量转为json对象,语法“json_encode(字符串变量)”;json_encode()函数用于对任何数据类型的变量进行json编码,将其转换成json格式的数据。
本教程操作环境:windows7系统、php7.1版,dell g3电脑
php中将字符串变量转化成json格式
<?phpheader("content-type:text/html;charset=utf-8;");$arr = array (‘version_code‘=>2,‘version_name‘=>‘updateversion‘,‘versoin_desc‘=>‘更新了地图功能‘,‘versoin_path‘=>‘http://nnddkj.com/busiot/apk/busiot.apk‘);echo json_encode($arr);?>
如上代码,即为将字符串变量转化成json格式输出,但是输出结果如下:
{"version_code":2,"version_name":"updateversion","versoin_desc":"\u66f4\u65b0\u4e86\u5730\u56fe\u529f\u80fd","versoin_path":"http:\/\/nnddkj.com\/busiot\/apk\/busiot.apk"}即数组中所有中文在json_encode之后都不见了或者出现\u2353等。
解决方法是用urlencode()函数处理以下,在json_encode之前,把所有数组内所有内容都用urlencode()处理一下,然用json_encode()转换成json字符串,最后再用urldecode()将编码过的中文转回来。
<?phpheader("content-type:text/html;charset=utf-8;");$arr = array (‘version_code‘=>2,‘version_name‘=>‘updateversion‘,‘versoin_desc‘=>urlencode(‘更新了地图功能‘),‘versoin_path‘=>urlencode(‘http://nnddkj.com/busiot/apk/busiot.apk‘));echo urldecode(json_encode($arr));?>
输出结果:{"version_code":2,"version_name":"updateversion","versoin_desc":"更新了地图功能","versoin_path":"http://nnddkj.com/busiot/apk/busiot.apk"}
搞定。。
附:json_decode对json格式的字符串进行编码,而json_encode对变量进行 json 编码
json_decode - 对json 格式的字符串进行编码
说明:
mixed json_decode ( string $json [, bool $assoc ] )
接受一个 j son 格式的字符串并且把它转换为 php 变量 ,$assoc,当该参数为 true 时,将返回 array 而非 object
推荐学习:《php视频教程》
以上就是php怎么将字符串变量转为json对象的详细内容。