PHP JSON

PHP allows us to encode and decode JSON by using json_encode() and json_decode functions.

  • json_encode - Returns the JSON representation of a value
  • json_decode - Decodes a JSON string

json_encode

string  json_encode ( mixed $value  [, int $options = 0[,int $depth = 512]])

Let's see the example to encode JSON.

<?php
 $array = array('a' => 'Apple', 'b' => 'Mango', 'c' => 'Banana', 'd' => 'Apricot', 'e' => 'Blackberry');
 echo json_encode($array);
?>
Output: {"a":"Apple","b":"Mango","c":"Banana","d":"Apricot","e":"Blackberry"}

json_decode

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

Let's see the example to decode JSON.

<?php
 $str = '{"a":"Apple","b":"Mango","c":"Banana","d":"Apricot","e":"Blackberry"}';
 var_dump(json_decode($str));
?>
Output: object(stdClass)#1 (5) { ["a"]=> string(5) "Apple" ["b"]=> string(5) "Mango" ["c"]=> string(6) "Banana" ["d"]=> string(7) "Apricot" ["e"]=> string(10) "Blackberry" }