PHP JSON

This tutorial will help you learn PHP JSON. Let's first see what PHP JSON is.

 

What is PHP JSON?

JSON is the acronym for JavaScript Object Notation. It is a syntax to store and exchange data. 

The JSON format is text-based and can be easily sent to and from a server. Therefore, it can be used as a data format by any programming language. 

 

PHP and JSON

PHP includes built-in functions for handling JSON. Let's first consider the following two functions:

  • json_encode()
  • json_decode()

 

PHP - json_encode()

This function can be used for encoding a value to JSON format.

Example:

<?php
$age = array("Peter"=>35, "Ben"=>37, "Joe"=>43);

echo json_encode($age);
?>

 

 

PHP - json_decode()

You can use the json_decode() function for decoding a JSON object into a PHP object or an associative array.

<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';

var_dump(json_decode($jsonobj));
?>

An object is returned by default by the json_decode() function. This function has a second parameter, and when it is set to true, it decodes the JSON objects into associative arrays. 

 

PHP - Looping Through the Values

With a foreach() loop, you can loop through the values. 

<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';

$obj = json_decode($jsonobj);

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