Today's Question:  What are bad parts of Windows 10?       GIVE A SHOUT

Technical Article => Web =>  PHP

Using JSON in PHP

 Peter     2012-05-06 06:04:42      10,735    1    0

Currently JSON has become one of the most popular data exchange formats. Many website APIs support it. Since PHP 5.2, PHP provides json_encode() and json_decode() method to handle JSON encoding and decoding.

1. json_encode()

This function is used to transform array and objects to JSON format. First let's look one array example.

        $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

  echo json_encode($arr);

the result is

{"a":1,"b":2,"c":3,"d":4,"e":5}

We look one example of object transformation.

        $obj->body = 'another post';

  $obj->id = 21;

  $obj->approved = true;

  $obj->favorite_count = 1;

  $obj->status = NULL;

  echo json_encode($obj);

the result is

        {
    "body":"another post",

    "id":21,

    "approved":true,

    "favorite_count":1,

    "status":null
  }

Since JSON can only accept UTF-8 encoded characters, so parameters of json_encode() must be utf-8 encoded, otherwise the result will be empty or null. So we need to take care when we use Chinese's GB2312 encoding or some other languages' ISO-8859-1 encoding.

2. Indexed array and associative array

PHP supports two kinds of arrays, one is indexed array which only stores the value, the other is associative array which stores name/value pairs.

Since JavaScript doesn't support associative array, so json_encode() will transform indexed array into array format, while transform associative array into object format.

For example, we have an indexed array

        $arr = Array('one', 'two', 'three');

  echo json_encode($arr);

the result will be

        ["one","two","three"]

If we have an associative array

        $arr = Array('1'=>'one', '2'=>'two', '3'=>'three');

  echo json_encode($arr);

the result will be

        {"1":"one","2":"two","3":"three"}

Note, data format has changed from [] to {}.

If you want to forcibly transform indexed array into object, you can

      json_encode( (object)$arr );

or

      json_encode ( $arr, JSON_FORCE_OBJECT );

3. Transformation of class

Here is a PHP class
      class Foo {

    const ERROR_CODE = '404';

    public $public_ex = 'this is public';

    private $private_ex = 'this is private!';

    protected $protected_ex = 'this should be protected';

    public function getErrorCode() {

      return self::ERROR_CODE;

    }

  }

now we do JSON transformation.

        $foo = new Foo;

  $foo_json = json_encode($foo);

  echo $foo_json;

the result is

        {"public_ex":"this is public"}

we can see that only public variables are transformed. All rest will be ignored.

4. json_decode()

To transform JSON data to PHP data structure. For example

       $json = '{"foo": 12345}';

  $obj = json_decode($json);

  print $obj->{'foo'}; // 12345

Usually, json_decode() will return a PHP object instead of array.

        $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

  var_dump(json_decode($json));

the result is a PHP object

        object(stdClass)#1 (5) {

    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)

  }

If we want to forcibly to transform JSON into an array, we need to add one more parameter true to json_decode().

        $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

  var_dump(json_decode($json,true));

the result is an associative array

        array(5) {

     ["a"] => int(1)
     ["b"] => int(2)
     ["c"] => int(3)
     ["d"] => int(4)
     ["e"] => int(5)

  }

5. Common mistakes of json_decode()

Following three JSON example have syntax errors. Where is the error?

        $bad_json = "{ 'bar': 'baz' }";

  $bad_json = '{ bar: "baz" }';

  $bad_json = '{ "bar": "baz", }';

the json_decode() will return null for the above three strings.

The first error is, delimiter of JSON can only be double quote, cannot be single quote. The second error is the name of the name/value pair of JSON must be surrounded with double quote. The last error is the last value cannot have trailing comma.

Also JSON can only be used to represent object and array, if we use json_decode() on a string or number, it will return null.

        var_dump(json_decode("Hello World")); //null

References

        * PHP Manual

  * Ed Finkler, JSON is Everybody's Friend

Original author : 阮一峰 Source : http://www.ruanyifeng.com/blog/2011/01/json_in_php.html

 Tags : JSON,PHP,json_decode(0,json_encode()   Read(10,735) Comment(1) Version(0)

  SAVE AS PDF   MARK AS READ   MARK AS IMPORTANT

 RELATED


 COMMENT  (TOTAL 1 COMMENT)


joelmob [Reply]@ 2012-05-07 08:59:42
Here is a snippet on how to get JSON from your SQL server with PHP and MySQLi

Nickname  
Email 
Comment

IKEA Bookbook

By sonic0002
IKEA 2015 Catalogue bookbook. Download a free copy or upload yourself to IKEA. Give you an advice, IKEA, be careful of the DOS attack. If you are in mainland China, please watch the video IKEA Bookbook. To be honest. A very creative design.It gets over 10 million visits in less than 15 days.

 CONTRIBUTE


Share your geeky stuff now.
You make the world better, the world makes us better.

 WRITE ARTICLE

 VERSION


No other version available yet.