top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

What are the encoding and decoding function for JSON in PHP, please explain with proper examples?

0 votes
31 views
What are the encoding and decoding function for JSON in PHP, please explain with proper examples?
posted Jul 9, 2017 by Saheb Pro

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

0 votes

Encoding JSON in PHP (json_encode)

PHP json_encode() function is used for encoding JSON in PHP. This function returns the JSON representation of a value on success or FALSE on failure.

Syntax

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

Parameters

value
− The value being encoded. This function only works with UTF-8 encoded data.

options
− This optional value is a bitmask consisting of 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

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

Output

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

Decoding JSON in PHP (json_decode)

PHP json_decode() function is used for decoding JSON in PHP. This function returns the value decoded from json to appropriate PHP type.

Syntax

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

Paramaters

json_string
− It is an encoded string which must be UTF-8 encoded data.

assoc
− It is a boolean type parameter, when set to TRUE, returned objects will be converted into associative arrays.

depth
− It is an integer type parameter which specifies recursion depth

options
− It is an integer type bitmask of JSON decode, JSON_BIGINT_AS_STRING is supported.

Example

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

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

Output

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)
}
answer Jul 11, 2017 by Sanam
Similar Questions
0 votes
{"general":{
 "round-corner":"0",
 "border-stroke":"2",
 "background-color":"#ffffff"
 }
}

I have this json string, I know that php variable names doesn't support dashes. So what to do in this case ?

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...