JSON In PHP

JSON

  • JSON (JavaScript Object Notation) is a lightweight data-interchange format. 
  • Humans can read and write it with ease.
  • Machines can quickly parse and generate it.
  • JSON is a text format that is completely language-independent.

JSON in PHP

The most common way to use JSON in PHP is to transform ordinary PHP objects or arrays into JSON data.

Let's make a PHP object.

$User = new stdClass();
$User->first_name = "XXX";
$User->last_name = "YYY";
$User->age = 32;
$User->city = "Testing";

Use the built-in PHP function "json_encode" to transform this PHP object into JSON.

$UserJson = json_encode($User);

The same function makes it simple to convert PHP arrays into JSON

$names = array("xx","yy","zz");
echo json_encode($names);
// output: ["xx","yy","zz"]

Use the "json_decode" method to convert JSON data back into a PHP object.

$json = '{"xxx":20,"yyy":30,"zzz":45}'
var_dump(json_decode($json));
/*
object (staclass) #1 (3) {
    ["xxx"] => int(20)
    ["yyy"] => int(30)
    ["zzz"]=> int(45)
}*/

Use the second parameter of the json_decode method and set it to true if you wish to transform JSON into an associative array rather than an object

$json = '{"xxx":20,"yyy":30,"zzz":45}'
var_dump(json_decode($json,true));
/*
array (3) {
    ["xxx"] => int(20)
    ["yyy"] => int(30)
    ["zzz"]=>  int(45)
}*/