Using JSON in PHP

Introduction

This article explains the use of JSON in PHP. JSON is like XML. JSON however represents data another way using the data types strings, objects, arrays, numbers, boolean (true and false) and null. Strings must be enclosed in double-quotes and keys are always strings in JSON.

{"name":"jojo", "age":30}

Here the key name corresponds to the string value and age corresponds to a string value in JSON. JSON arrays are enclosed in braces and values are separated by commas. Like this:

{"jojo", 30}

But a PHP array is very similar to an object and PHP has the built-in functions json_encode and json_decode for encoding and decoding JSON. The json_encode function returns the JSON representation of a value and Json_decode() function decodes a JSON string.

Example

Encoding PHP Data types to JSON and decoding back to PHP data types:

<?php

$data_types = array(2.1, 4, NULL, true, false, "Hello", new StdClass(), array());

$Jsons = json_encode($data_types);

$Deco = json_decode($Jsons);

?>

<p><font color="#0000FF">JSON Representation:</font><br/>

<pre>

<?php var_dump($Jsons); ?>

</pre>

</p>

<p><font color="#0000FF">PHP Representation:</font><br/>

<pre>

<?php var_dump($Deco); ?>

</pre>

</p>

Output

cal.jpg

Example

A PHP Nested Array is first being encoded to JSON and then decoded back to PHP.

<?php

$article = array(

array("Author" => "Vinod kumar",

"Title" => "JSON in PHP",

"Year" => 2013),

array("Author" => "Nitin",

"Title" => "TypeScript",

"Year" => 2012),

array("Author" =>"Sharad",

"Title" => ".Net",

"Year" => 2011),

array("Author" => "Manish",

"Title" => "SQL",

"Year" => 2009),

array("Author" => "Phrabhaker",

"Title" => "Windows App",

"Year" => 2013),

);

$json_article = json_encode($article);

$decoded_json_article = json_decode($json_article);

?>

<pre>

<p><font color="#0000FF">JSON Representation:</font><br/>

<?php var_dump($json_article); ?>

<p><font color="#0000FF">PHP Representation:</font><br/>

<?php var_dump($decoded_json_article); ?>

</pre>

Output

cal1.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all