JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate.
It's commonly used for transmitting data between a web server and a web application.
JSON provides a simple and flexible way to exchange data between different programming languages and platforms.
PHP JSON use two type of functions
- json_encode() - Array To JSON String
- json_decode() - JSON String to Array
Example - json_encode()
<?php
$udata = array(
'name' => 'Tutorials on Web',
'age' => 30,
'email' => 'info@tutorialsonweb.com'
);
$jsonData = json_encode($udata);
echo $jsonData;
?>
- We have a PHP associative array $udata containing some sample data.
- We use the json_encode() function to convert the PHP array into a JSON string.
OutPut:
{"name":"Tutorials on Web","age":30,"email":"info@tutorialsonweb.com"}
Example - json_decode()
<?php
$jsondata = '{"name":"Tutorials on Web","age":30,"email":"info@tutorialsonweb.com"}';
$data = json_decode($jsondata, true);
?>
- We have a JSON string $jsonData.
- We use the json_decode() function to convert the JSON string into a PHP associative array.
OutPut:
Name: Tutorials on Web
Age: 30
Email: info@tutorialsonweb.com