Home > Backend Development > PHP Problem > How to use json method in php

How to use json method in php

藏色散人
Release: 2023-03-03 14:06:01
Original
2477 people have browsed it

In PHP, you can operate json through the "json_encode()" and "json_decode()" functions, whose syntax is "json_encode($arr);" and "json_decode($json)" respectively.

How to use json method in php

Recommended: "PHP Video Tutorial"

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()                                                                                                                                                                                                                                                     .

The code is as follows:

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

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

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

json_decode()

The code is as follows:

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

Output result:

Normally, json_decode() always returns a PHP object.

Converted to an array:

The code is as follows:

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

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

Related labels:
php
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