PHP development basic tutorial JSON

1. Environment configuration

The JSON extension has been built-in in php5.2.0 and above.


2. JSON function

65.png


##3 , json_encode

PHP json_encode() is used to JSON encode variables. This function returns JSON data if executed successfully, otherwise it returns FALSE.

Syntax

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

Parameters

value: The value to encode. This function is only valid for UTF-8 encoded data.

options: Binary mask consisting of the following constants: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT

Example

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

The code is as follows

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

The output result is shown on the right

2. The following example demonstrates how to convert PHP objects into JSON format data

The code is as follows

<?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', "8/5/1974 12:20:03 p");
   $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03"));

   echo json_encode($e);
?>

The output results are shown on the right


Note:

There may be a caveat when running locally. The reason is that the data type is inconsistent with the expected one.

The Strtotime() function is used Parses any English text date or time description into a Unix timestamp (number of seconds since January 1 1970 00:00:00 GMT).


##4.json_decode

PHP json_decode () function is used to decode JSON-formatted strings and convert them into PHP variables.

Syntax:

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

Parameters

json_string: JSON string to be decoded, must be UTF-8 encoded data
  • assoc: When this parameter is TRUE, an array will be returned, and when FALSE, an object will be returned.
  • depth: Integer type parameter, which specifies the recursion depth
  • options: Binary mask, currently only supports JSON_BIGINT_AS_STRING.
  • Example
The following example demonstrates how to decode JSON data: The code is as follows

<?php
   $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
   //默认返回对象
   echo "<pre>";
   var_dump(json_decode($json));
   //返回数组
   var_dump(json_decode($json, true));
   echo "</pre>"
?>

The output is shown on the right

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