1 min read

PHP JSON Handling

JSON (JavaScript Object Notation) is a lightweight data-interchange format. PHP has built-in functions to handle JSON.


1. Encoding JSON

The json_encode() function is used to convert a PHP array or object into a JSON string.

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

echo json_encode($age);
// Outputs: {"Peter":35,"Ben":37,"Joe":43}

2. Decoding JSON

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

Decoding to Object (Default)

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

$obj = json_decode($jsonobj);

echo $obj->Peter; // Outputs: 35

Decoding to Associative Array

Pass true as the second parameter to return an associative array instead of an object.

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

$arr = json_decode($jsonobj, true);

echo $arr["Peter"]; // Outputs: 35

3. Handling Errors

You can use json_last_error() or json_last_error_msg() to check for errors during encoding or decoding.

programming/php/php