Today's Question:  What are you most afraid of as a programmer?       GIVE A SHOUT

Technical Article => Web =>  PHP

Using JSON in PHP

 Peter     2012-05-06 06:04:42      10,962    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


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",





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


If we have an associative array

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

  echo json_encode($arr);

the result will be


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

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

      json_encode( (object)$arr );


      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}';


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}';


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


        * PHP Manual

  * Ed Finkler, JSON is Everybody's Friend

Original author : 阮一峰 Source :





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


Nesting if-else in Skype source code

By sonic0002
One piece of source code of Skype. Is this code snippet written by interns?


No other version available yet.