Home > Backend Development > PHP Tutorial > How to use JSON in php, how to use phpJSON_PHP tutorial

How to use JSON in php, how to use phpJSON_PHP tutorial

WBOY
Release: 2016-07-13 09:55:13
Original
968 people have browsed it

How to use JSON in php, how to use phpJSON

Starting from version 5.2, PHP natively provides json_encode() and json_decode() functions. The former is used for encoding, and the latter is used for decoding.
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 result:

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

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; 
Copy after login
Output result:

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

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));



The above is the entire content of this article, I hope you all like it.

http://www.bkjia.com/PHPjc/992544.html

truehttp: //www.bkjia.com/PHPjc/992544.htmlTechArticleHow to use JSON in php. Starting from version 5.2, PHP natively provides json_encode() and json_decode( ) function, the former is used for encoding and the latter is used for decoding. json_encode() This...
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