Home >>Json Tutorial >PHP JSON Example

PHP JSON Example

JSON Functions

Function Description
json_encode( ) Returns the JSON representation of a value
json_decode( ) Decodes a JSON string.
json_last_error( ) Returns the last error occurred.

PHP json_encode( )

In PHP, json_encode( ) function is used to encode JSON into PHP. In other words we can say that json_encode( ) function convert PHP variables into JSON String.

Syntax

  string json_encode(mixed value,[int options=0]  

Ex 1

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

    echo json_encode($array);  

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

Ex 2

<?php  

   $array = array("Name"=>"Vineet","Profile"=>"Developer","Mobile"=>"9015501897");  
 
    echo json_encode($array);   

?>
 
Output {"Name":"Vineet","Profile":"Developer","Mobile":"9015501897"}

PHP json_decode( )

In PHP json_decode( ) function is used to decode JSON into PHP. In other words we can say that json_decode( ) function convert JSON string into PHP variables.

Syntax

mixed json_decode(string json,[bool assoc = false,[int depth=512]]

Ex 1

<?php  

   $json1 = '{"a":1,"b":2,"c":3,"d":4,"e":5}';  
   
  var_dump(json_decode($json1));
 
  var_dump(json_decode($json1, 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) }

Ex 2

<?php  

   $json2 = '{"Name":"Vineet","Profile":"Developer","Mobile":"9015501897"}';    
 
  var_dump(json_decode($json2, true));

?>
Output array(3) { ["Name"]=> string(6) "Vineet" ["Profile"]=> string(9) "Developer" ["Mobile"]=> string(10) "9015501897" }

No Sidebar ads