i

PHP Tutorial

JSON

JSON stands for JavaScript Object Notation and is a minimal and readable format used for structuring the data. It is used to transmit data between a web application and a server and is used as an alternative to XML.

JSON format is text only and you can save it as a text file. Also, you can easily access the JSON file and sent it from a server. It can be used by any programming language as a data format. In PHP you can easily handle JSON with two predefined functions.

1. json_encode() is used to call JSON data into an PHP array.

For example:

$color = array("Black", "Green”, "Pink");

echo json_encode($color);
?>

The above code will output the data in JSON format as: [“Black”, “Green”, “Pink”]

$user = array("name"=>’Joe’, “age"=>23);

echo json_encode($user);
?>

The above code will output the data in JSON format as: {“name” : ‘Joe’ , “age” : 23}

2. json_decode() is used to call PHP array into JSON data.

For example:

$json_data = '{"name": ‘Ben’, "age":29}';
 
var_dump(json_decode($json_data));
?>

The above code will output the data in PHP associative array form as:

object(stdClass)#1 (3) { ["name"]=> string(‘Ben’) ["age"]=> int(29) }

You can access the decode values as below:

$json_data = '{"name": ‘Ben’, "age":29}';
$object = json_decode($json_data);

echo $object ->name;

echo “
”;

echo $object ->age;

?>

The output of the above php script will be:

Ben

29

You can also loop through the array values to print them automatically as below:

$json_age = '{"John":23,"Sam":26,"Roy":28}';

$obj = json_decode($json_age);

foreach($obj as $key => $value) {
  echo $key . " => " . $value . "
";
}
?>

The output of the above php loop will be:

John => 23

Sam => 26

Roy => 28