Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

PHP JSON


May 11, 2021 PHP


Table of contents


PHP JSON

In this section we'll show you how to encode and decode JSON objects using the PHP language.


Environment configuration

JSON extensions are already built in php5.2.0 and above.


JSON function

Function Describe
json_encode JSON encoding variables
json_decode The string in the JSON format is decoded and converted to a PHP variable
json_last_error Returns the last error that occurred

json_encode

PhP json_encode () is used to encode the variable JSON, which returns false if the execution successfully returns the JSON data.

Grammar

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

Parameters

  • Value: The value to encode. This function is only valid for UTF-8 encoded data.
  • Options: Binary masks 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

Instance

The following example shows how to convert a PHP array to JSON format data:

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

The above code execution results are:

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

The following example shows how to convert PHP objects to JSON format data:

?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 above code execution results are:

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

json_decode

The PHP json_decode() function is used to decode strings in JSON format and convert them to PHP variables.

Grammar

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

Parameters

  • json_string: The JSON string to be decoded must be UTF-8 encoded data

  • Assoc : When the argument is TRUE, an array is returned, and an object is returned when FALSE.

  • Depth : An argument of an integer type that specifies a recursive depth

  • Options : Binary mask, currently only supports JSON_BIGINT_AS_STRING.

Instance

The following example shows how to decode JSON data:

<?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 results are:

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)
}