Open In App

What is use of the json_encode() and json_decode() functions in PHP?

In PHP, json_encode() and json_decode() are essential functions for handling JSON (JavaScript Object Notation) data. JSON is a lightweight data-interchange format widely used for transmitting data between a server and a client in web applications.

Syntax:

// Encode PHP data to JSON format
$jsonString = json_encode($phpData);

// Decode JSON string to PHP data
$phpData = json_decode($jsonString);

Difference between json_encode() and json_decode()

json_encode() json_decode()
Encodes PHP data into JSON format Decodes JSON string into PHP data
Returns a JSON string Returns a PHP data structure
Accepts optional parameters to modify encoding behavior Accepts optional parameters to modify decoding behavior

Features:

Example:

// Encode PHP array to JSON string
$data = array("name" => "John", "age" => 30);
$jsonString = json_encode($data);

// Decode JSON string to PHP array
$decodedData = json_decode($jsonString, true); // true to return associative array

echo $jsonString; // Output: {"name":"John","age":30}
print_r($decodedData); // Output: Array ( [name] => John [age] => 30 )
Article Tags :