JSON with PHP


JSON with PHP

The PHP programming language is used to create JSON objects. Let's begin by setting up the environment where we'll be programming in PHP for JSON.

Environment

The JSON extension is packed and compiled into PHP by default as PHP 5.2.0.

JSON Functions

Function Libraries
json encode Returns a value's JSON representation.
json_decode This function decodes a JSON string.
json_last_error The last error that occurred is returned.
  • JSON encoding (json encode) in PHP
  • In PHP, the json encode() function is used to encode JSON. On success, this method returns the JSON representation of a value; on failure, it returns FALSE.
  • json encode ($value [, $options = 0]) is a syntax string.
  • value of parameters The value that is being encoded. This function only works with data that has been encoded in UTF-8.
  • JSON HEX QUOT, JSON HEX TAG, JSON HEX AMP, JSON HEX APOS, JSON HEX APOS, JSON HEX APOS, JSON HEX APOS, JSON HEX APOS, JSON HEX APOS, JSON HEX APOS, JSON HEX APOS, JSON HEX APOS,

JSON NUMERIC CHECK, JSON PRETTY PRINT, JSON UNESCAPED SLASHES, and JSON FORCE OBJECT are some of the JSON functions.

Example

The example below demonstrates how to convert an array into JSON using PHP.

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

This will yield the following result while running: "a":1,"b":2,"c":3,"d":4","e":5"

The following example demonstrates how to convert PHP objects to JSON.

<?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); ?>

This will generate the following result while running: "name":"sachin","hobbies":"sports","birthdate":"08/05/1974 12:20:03 pm"

PHP's json decode function decodes JSON.

PHP In PHP, the json decode() function is used to decode JSON. This function converts the decoded json value to the proper PHP type.

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

json string is an encoded string that must contain UTF-8 encoded data.

depth is an integer type parameter that indicates the depth of recursion options. JSON BIGINT AS STRING is an integer type bitmask that can be used to decode JSON.

Example

The sample below demonstrates how PHP may be used to decode JSON objects.

<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json)); var_dump(json_decode($json, true)); ?>

While executing, it will produce the following result −

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