PHP

PHP Json Encode And Decode Example

Json is an abbreviation for JavaScript Object Notation. It is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language (the way objects are built in JavaScript).
In this example we will create a simple or trivial web app that shows us how to manipulate Json with PHP( Encode and decode Json data with PHP ).
For this example we will use:

  • A computer with PHP >= 5.5 installed
  • notepad++

 
 

1. Getting Started

JSON (JavaScript Object Notation) is a data variable format that is both lightweight and human-readable. JSON can be handled on the client side with javascript, this makes it suitable for server side and client side communication. JSON is gradually replacing (or as replaced )XML for transferring data from server to client and has become popular with web developers. Technologies like AJAX, Google Map API ( and many more, too numerous to be mentioned here.) allows for data to be relayed back to the client in JSON.
JSON is built on two structures:

  • A collection of name/value pairs.
  • An ordered list of values.

The light-weight attribute or character of JSON makes it preferable to XML as it reduces bandwidth consumption and verbosity (less bytes are transmitted when data format is in JSON unlike XML which uses more bytes). JSON has its limitations, we can’t transfer natives data types like dates.

We have to convert the date to a supported type like strings, integer or UNIX Timestamp. Data types that can be used with JSON are strings, integers, null, boolean, arrays and objects.

index.html

<!DOCTYPE html> 
 <html lang="en"> 
 <head>    
 <title>Example of JSON Format</title>     
</head>
 <body>    
 <h1>
Example of JSON Format
  </h1>
    


{ 
  "first name": "John",
  "last name": "Smith", 
  "married": "Yes",
  "Num Of children": 1,
  "Sex": "MALE",
  "address": { 
"street address": "21 2nd Avenue Street mushin", 
"city": "Barracks", 
"state": "BA", 
"postal code": 20081
}, 
"phone numbers": [ 
"212 555-1234", 
"646 555-4567" ] 
}

  </body> 
</html>


An Example of JSON formatted text in an HTML document. Some characteristics of JSON are:

  • It is language independent.
    Note: JSON format is text only like its companion XML. Text can be read by any programming language.
  • It is light weight
  • It is self describing and very easy to understand.
  • Compared to XML, JSON is faster and easier to implement.

1.1 JSON Encoding With PHP

To encode data into JSON in PHP we use the function below:

string json_encode ( mixed
$value, int $options, int $depth]] )

This function call on any data will return an encoded JSON string on success and FALSE on failure.
Note: All string data must be UTF-8 encoded.
$value Represents the data to be encoded.
$options Represents 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
  • JSON_PRESERVE_ZERO_FRACTION
  • JSON_UNESCAPED_UNICODE
  • JSON_PARTIAL_OUTPUT_ON_ERROR.

The behavior of these constants can be found here

$depth is the maximum depth and this value must be greater than zero.
Lets look at a simple example

index.html

<!DOCTYPE html> 
 <html lang="en"> 
 <head>    
 <title>Example of JSON Format</title>     
</head>
 <body>    
 <h1>
Example of JSON Format
  </h1>

<?php 

$lang= array("PHP", "Java", "JS", "HTML", "Perl", ".NET");
// Returns ["PHP","Java","JS","HTML","Perl",".NET"]
echo json_encode($lang);
echo "<br>";
//[{"php":"PHP","Java":"JAVA","HTML":"HTML","perl":"PERL","net":"NET"}]
$lang=array(array("php" => "PHP", "Java" => "JAVA", "HTML" => "HTML", "perl" => "PERL", "net" => "NET"));
 echo json_encode($lang);
echo "<br>";
// Returns: {"apples":true,"bananas":null}
 echo json_encode(array("PHP" => true, "JAVA" => true, " Perl" => FALSE, "Basic" => null)); 

?>
</body>
</html>

You can see that boolean and strings are not converted to strings, they are converted to the right types. Another Example Below:

index2.php

<!DOCTYPE html> 
 <html lang="en"> 
 <head>    
 <title>Example of JSON Format</title>     
</head>
 <body>    
 <h1>
Example of JSON Format
  </h1>

<?php 
class lang {   
public $java = "JAVA";    
public $php  = "PHP";     
public $html = "HTML";
public $js = "JAVASCRIPT";
public $perl = "PERL";
public $dates = "";
 }
$lan = new lang();
$lan->dates = new DateTime();

/* Returns:    
{"java":"JAVA","php":"PHP","html":"HTML","js":"JAVASCRIPT","perl":"PERL","dates":{"date":"2016-11-18 01:27:34.000000","timezone_type":3,"timezone":"Asia\/Jakarta"}}
 */

 echo json_encode($lan);


 ?>
</body>
</html>

In the example script we actually print out the JSON value of an object. In PHP objects are inspected and their public attributes are converted.

1.2 JSON Decoding With PHP

Decoding JSON is as simple as encoding it. To decode JSON in PHP we use the function below:

mixed json_decode ( string
$json, bool $asso )

This function takes a JSON encoded string and converts it into a PHP variable. $json is the json string being decoded. This function only works with UTF-8 encoded strings.
assoc is a boolean variable when set to TRUE, returned objects will be converted into associative arrays.
This function returns the value encoded in json in appropriate PHP type. Values true , false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

index3.php

<!DOCTYPE html> 
 <html lang="en"> 
 <head>    
 <title>Example of JSON Format</title>     
</head>
 <body>    
 <h1>
Example of JSON Format
  </h1>
<?php
/*the function call both returns
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) }
*/

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

echo "<br>";

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

</body>
</html>

The above example decodes a JSON string into PHP variable. According to the official PHP website var_dump displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.

All public, private and protected properties of objects will be returned in the output unless the object implements a __debugInfo() method (implemented in PHP 5.6.0).

2. Summary

In this tutorial we learnt about the nitty-gritty of json. We also learnt how to encode data to JSON and decide JSON into a PHP variable.

3. Download the source code

Download
You can download the full source code of this example here: phpjsonencodeanddecode

Olayemi Odunayo

I am a programmer and web developer, who has experience in developing websites and writing desktop and mobile applications. I have worked with both schematic and schemaless databases. I am also familiar with third party API and working with cloud servers. I do programming on the client side with Java, JavaScript, html, Ajax and CSS while I use PHP for server side programming.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button