Easy Tutorial
❮ Php Use Statement Func String Wordwrap ❯

PHP JSON

This section will introduce how to encode and decode JSON objects using PHP.


Environment Configuration

The JSON extension is built-in for PHP versions 5.2.0 and above.


JSON Functions

Function Description
json_encode Encodes a variable into JSON format
json_decode Decodes a JSON formatted string into a PHP variable
json_last_error Returns the last error that occurred

json_encode

The PHP function json_encode() is used to encode a variable into JSON. It returns JSON data if successful, otherwise FALSE.

Syntax

string json_encode ( $value [, $options = 0 ] )

Parameters

Example

The following example demonstrates how to convert a PHP array into JSON format:

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

The result of the above code is:

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

The following example demonstrates how to convert a PHP object into JSON format:

Example

<?php
   class Emp {
       public $name = "";
       public $hobbies  = "";
       public $birthdate = "";
   }
   $e = new Emp();
   $e->name = "sachin";
   $e->hobbies  = "sports";
   $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03"));

   echo json_encode($e);
?>

The result of the above code is:

{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}

Using JSON_UNESCAPED_UNICODE Option

<?php
   $arr = array('tutorialpro' => 'tutorialpro.org', 'taobao' => '淘宝网');
   echo json_encode($arr); // Encodes Chinese characters
   echo PHP_EOL;  // Line break
   echo json_encode($arr, JSON_UNESCAPED_UNICODE);  // Does not encode Chinese characters
?>

The result of the above code is:

{"tutorialpro":"\u83dc\u9e1f\u6559\u7a0b","taobao":"\u6dd8\u5b9d\u7f51"}
{"tutorialpro":"tutorialpro.org","taobao":"淘宝网"}

json_decode

The PHP function json_decode() is used to decode a JSON formatted string into a PHP variable.

Syntax

mixed json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

Parameters

Example

The following example demonstrates how to decode JSON data:

Example

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

   var_dump(json_decode($json));
   var_dump(json_decode($json, true));
?>

The above code execution result is:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
❮ Php Use Statement Func String Wordwrap ❯