How to convert string variable to json object in php

青灯夜游
Release: 2023-03-09 20:30:02
Original
4723 people have browsed it

In PHP, you can use the json_encode() function to convert string variables into json objects, the syntax is "json_encode (string variable)"; the json_encode() function is used to JSON encode variables of any data type , convert it into JSON format data.

How to convert string variable to json object in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

Convert string variables into Json format in PHP

<?php
header("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);
?>
Copy after login

The above code is to convert the string variable into json format for output, but the output result is as follows:

{"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等。
Copy after login

The solution is to use the urlencode() function to process the following, before json_encode, All contents in all arrays are processed with urlencode(), then converted into json strings using json_encode(), and finally converted back to encoded Chinese using urldecode().

<?php
header("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));
?>
Copy after login

Output result: {"Version_code":2,"Version_name":"UpdateVersion","Versoin_desc":"Updated map function","Versoin_path":"http://nnddkj.com/BusIot /APK/BusIot.apk"}

Done. .

Attachment: json_decode encodes strings in JSON format, while json_encode encodes variables in JSON

json_decode - encodes strings in JSON format

Description:

mixed json_decode ( string $json [, bool $assoc ] )
Copy after login

Accepts a JSON format string and converts it into a PHP variable, $assoc. When this parameter is TRUE, an array will be returned instead of an object

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to convert string variable to json object in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template