Home  >  Article  >  php教程  >  A brief analysis of json_encode() and json_decode()_php basics in php

A brief analysis of json_encode() and json_decode()_php basics in php

WBOY
WBOYOriginal
2016-05-16 08:59:514835browse

json_encode()                                                                                         

This function is mainly used to convert arrays and objects into json format.

Copy code The code is as follows:

$arr = array ('a'=>' a','b'=>'b','c'='c','d'=>'d','e'='e');
echo json_encode($arr);

Output results:

A brief analysis of json_encode() and json_decode()_php basics in php

json only accepts utf-8 encoded characters, and the parameters of json_encode() must be utf-8 encoded.

Copy code The code is as follows:

class person
{
public $ name;
public $age;
public $height;
function __construct($name,$age,$height)
{
$this->name = $name;
$ this->age = $age;
$this->height = $height;
}
}

$obj = new person("zhangsan",20,100);
$foo_json = json_encode($obj);
echo $foo_json;

Output results:

A brief analysis of json_encode() and json_decode()_php basics in php

When the attributes in the class are private variables, they will not be output.

json_decode()                                                                                        

This function is used to convert json text into the corresponding PHP data structure.

Copy code The code is as follows:

$json = '{"a":"hello","b":"world","c":"zhangsan","d":20 ,"e":170}';
var_dump(json_decode($json));

Output results:

A brief analysis of json_encode() and json_decode()_php basics in php

Normally, json_decode() always returns a PHP object.

Convert to array:

Copy code The code is as follows:

$json = '{"a":"hello ","b":"world","c":"zhangsan","d":20,"e":170}';
var_dump(json_decode($json,ture));

A brief analysis of json_encode() and json_decode()_php basics in php

Statement:
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