Use of JSON in php

Source: Internet
Author: User

Starting from version 5.2, PHP provides native 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 to json format.

$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. The json_encode () parameter 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;

Output result:

When the attribute in the class is a private variable, it is not output.

Json_decode ()

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

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

Output result:

In general, json_decode () always returns a PHP Object.

Convert to an array:

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

 

 

 

Reprinted please indicate the source: http://www.cnblogs.com/yydcdut/p/3751141.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.