Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP JSON

What is JSON?

JSON, which stands for JavaScript Object Notation, is a syntax for storing and exchanging data.

Being a text-based format, JSON can be easily transmitted to and from a server and utilized as a data format by any programming language.

PHP and JSON

PHP provides built-in functions for handling JSON.

The primary functions are:

  • json_encode()
  • json_decode()

 

PHP – json_encode()

The json_encode() function is used to convert a value into JSON format.

Example

This example demonstrates how to encode an associative array into a JSON object:

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

echo json_encode($age);
?>

Example

This example illustrates how to encode an indexed array into a JSON array:

<?php
$cars = array(“Volvo”“BMW”“Toyota”);

echo json_encode($cars);
?>

PHP – json_decode()

The json_decode() function is used to convert a JSON object into a PHP object or an associative array.

Example

This example shows how to decode JSON data into a PHP object:

<?php
$jsonobj = ‘{“Peter”:35,”Ben”:37,”Joe”:43}’;

var_dump(json_decode($jsonobj));
?>

By default, the json_decode() function returns an object. However, if you set the second parameter to true, JSON objects will be decoded into associative arrays.

Example

This example demonstrates how to decode JSON data into a PHP associative array:

<?php
$jsonobj = ‘{“Peter”:35,”Ben”:37,”Jo

e”:43}’;

var_dump(json_decode($jsonobj, true));
?>

PHP – Accessing the Decoded Values

Here are two examples of how to access the decoded values from both an object and an associative array:

Example

This example demonstrates how to access values from a PHP object:

<?php
$jsonobj = ‘{“Peter”:35,”Ben”:37,”Joe”:43}’;

$obj = json_decode($jsonobj);

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

Example

This example illustrates how to access values from a PHP associative array:

<?php
$jsonobj = ‘{“Peter”:35,”Ben”:37,”Joe”:43}’;

$arr = json_decode($jsonobj, true);

echo $arr[“Peter”];
echo $arr[“Ben”];
echo $arr[“Joe”];
?>

PHP – Looping Through the Values

You can also iterate through the values using a foreach() loop:

Example

This example demonstrates how to loop through the values of a PHP object:

<?php
$jsonobj = ‘{“Peter”:35,”Ben”:37,”Joe”:43}’;

$obj = json_decode($jsonobj);

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

Example

This example illustrates how to loop through the values of a PHP associative array:

<?php
$jsonobj = ‘{“Peter”:35,”Ben”:37,”Joe”:43}’;

$arr = json_decode($jsonobj, true);

foreach($arr as $key => $value) {
  echo $key . ” => “ . $value “<br>”;
}
?>