JSON in PHP: How to Encode, Decode and Retrieve all JSON Values

Here is How to Encode, Decode and Retrieve all JSON Values if you are using JSON in PHP for storing or exchanging data

How to Use JSON In PHP?

JSON full form is JavaScript Object Notation and we use it for storing and exchanging data normally from server to server.

Even most APIs available on the internet use this as standard when it needs to exchange data via a single file.

Suggested: PHP Filters: How to use filters for Validation & Sanitization

Even though its name is JavaScript Object notation, it can be used by any programing language.

PHP also has some built-in Functions that we use to handle JSON.

There are mainly two functions that are in focus here-

  • json_encode(): This is for encode value to JSON format.
  • json_decode(): This is for decode a JSON object into a PHP object or an associative array.

Encode JSON In PHP

To encode a value to JSON format we use json_encode() PHP.

Here is a simple example, of how you can encode to a JSON object:

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

echo json_encode($age);

Decode JSON in PHP

We learned how to encode a PHP object into JSON but what about decoding an already existing JSON object to a PHP object.

For that purpose, we do use function json_decode().

Here is a simple example of decoding a JSON object into the PHP associate array-

$ages = '{"Peter":35,"Ben":37,"Joe":43}';

var_dump(json_decode($ages, true));

How to Access Decoded Values

We can decode the JSON object to a PHP array following the previous example, but how do we retrieve the value of each object?

Here is How-

$ages = '{"Peter":35,"Ben":37,"Joe":43}';

$obj = json_decode($ages));

echo $obj->Peter;
echo $obj->Ben;
echo $obj->Joe;

The data stored there are in key-value pairs so calling the key will retrieve its value.

How to Loop Trough Values

Echoing out or printing each value one by one could be exhausting and not ideal if you want to retrieve all values.

For purpose like that loops exist, using for each loop we key loop thru all values like this-

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

$obj = json_decode($jsonobj);

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

Rahul Bodana passionately shares knowledge through tutorials on programming, investment, trading, gaming, and writing, aiming to empower others with valuable insights and how-to guides.