0
0
PHPprogramming~5 mins

JSON encoding and decoding in PHP

Choose your learning style9 modes available
Introduction

JSON encoding and decoding lets you turn PHP data into a string format that computers can share easily, and then turn it back into PHP data.

When you want to send PHP data to a web browser or another program.
When you receive data from a web service and want to use it in PHP.
When you want to save PHP data in a file or database in a simple text format.
When you need to exchange data between different programming languages.
Syntax
PHP
$jsonString = json_encode($phpData);
$phpData = json_decode($jsonString, true);

json_encode() converts PHP data (like arrays or objects) into a JSON string.

json_decode() converts a JSON string back into PHP data. Use true as the second argument to get an array instead of an object.

Examples
This turns a PHP array into a JSON string.
PHP
$data = ['name' => 'Anna', 'age' => 25];
$json = json_encode($data);
echo $json;
This turns a JSON string back into a PHP array.
PHP
$json = '{"name":"Anna","age":25}';
$data = json_decode($json, true);
print_r($data);
Decoding without true returns an object. You can access properties with ->.
PHP
$object = json_decode($json);
echo $object->name;
Sample Program

This program shows how to encode a PHP array into JSON and then decode it back to a PHP array.

PHP
<?php
// Create PHP array
$user = ['username' => 'johndoe', 'email' => 'john@example.com', 'active' => true];

// Convert PHP array to JSON string
$jsonString = json_encode($user);
echo "JSON string:\n" . $jsonString . "\n\n";

// Convert JSON string back to PHP array
$decodedArray = json_decode($jsonString, true);
echo "Decoded PHP array:\n";
print_r($decodedArray);
?>
OutputSuccess
Important Notes

JSON only supports certain data types: strings, numbers, arrays, objects, booleans, and null.

When decoding, use true as the second argument to get an associative array instead of an object.

Always check if json_encode() or json_decode() returns false to catch errors.

Summary

Use json_encode() to turn PHP data into a JSON string.

Use json_decode() to turn a JSON string back into PHP data.

JSON is a simple way to share data between programs and languages.