This tutorial covers the basic details of the PHP json_encode function. It gives examples of decoding JSON string input to a PHP array.
It also describes this PHP JSON function‘s conventions, rules, and limitations. First, let’s see a quick example of converting JSON to an array.
This example has a JSON string that maps the animal with its count. The output of converting this JSON will return an associative array.
See this online demo to get the converted array result from a JSON input.
View demo
It uses PHP json_decode() with boolean true as its second parameter. The JSON will be converted into a PHP array with these decoding params.
<?php
// JSON string in PHP Array
$jsonString = '{"Lion":101,"Tiger":102,"Crocodile":103,"Elephant":104}';
$phpArray = json_decode($jsonString, true);
// display the converted PHP array
var_dump($phpArray);
?>
array(4) {
["Lion"]=>
int(101)
["Tiger"]=>
int(102)
["Crocodile"]=>
int(103)
["Elephant"]=>
int(104)
}
See the diagram that shows the input JSON string and the output stdClass object of the JSON decoding. In the previous article, we have seen examples of the reverse operation that is converting a PHP array to a JSON string.
This native PHP function decodes the JSON string into a parsable object tree or an array. This is the syntax of this function.
json_decode(
string $json,
?bool $associative = null,
int $depth = 512,
int $flags = 0
): mixed
You can find more about this function in the official documentation online.
This program has a minute change of not setting the boolean flag to the PHP json_decode function. This will return a PHP stdClass object tree instead of an array.
<?php
// JSON string in PHP Array
$jsonString = '{"name":"Lion"}';
$phpObject = json_decode($jsonString);
print $phpObject->name;
?>
Lion
The following JSON string is a valid JSON object in JavaScript but not in PHP. The issue is the single quote. It should be changed to a double quote.
If you want to see the JavaScript example to read and display JSON data the linked article has the code.
<?php
// 1. key and value should be within double quotes
$notValidJson = "{ 'lion': 'animal' }";
json_decode($notValidJson); // will return null
// 2. without a quote is also not allowed
$notValidJson = '{ lion: "animal" }';
json_decode($notValidJson); // will return null
// 3. should not have a comma at the end
$notValidJson = '{ "lion": "animal", }';
json_decode($notValidJson); // will return null
?>
This can be achieved by setting the bitmask parameter of the predefined JSON constants.
The JSON_BIGINT_AS_STRING constant is used to convert JSON with data having large integers.
<?php
$jsonString = '{"largeNumber": 12345678901234567890123}';
var_dump(json_decode($jsonString, false, 512, JSON_BIGINT_AS_STRING));
?>
object(stdClass)#1 (1) {
["number"]=>
string(20) "12345678901234567890123"
}
The function json_last_error() returns details about the last error occurrence. The following example handles the possible error cases of this PHP JSON function.
<?php
$jsonString = '{"Lion":101,"Tiger":102,"Crocodile":103,"Elephant":104}';
json_decode($jsonString);
switch (json_last_error()) {
case JSON_ERROR_DEPTH:
echo 'Error: Nesting limit exceeded.';
break;
case JSON_ERROR_STATE_MISMATCH:
echo 'Error: Modes mismatch.';
break;
case JSON_ERROR_CTRL_CHAR:
echo 'Error: Unexpected character found.';
break;
case JSON_ERROR_SYNTAX:
echo 'Error: Syntax error, invalid JSON.';
break;
case JSON_ERROR_UTF8:
echo 'Error: UTF-8 characters incorrect encoding.';
break;
default:
echo 'Unexpected error.';
break;
}
?>
<?php
$jsonString = '{"0": "No", "1": "Yes"}';
// convert json to an associative array
$array = json_decode($jsonString, true);
print json_encode($array) . PHP_EOL;
?>
["No","Yes"]
The PHP object is now changed to a PHP array. You may not expect it.
Encode -> Decode -> Encode
The above will not return the data to its original form.
The decoding output to PHP arrays and encoding from PHP arrays are not always symmetrical. But, the output of decoding from stdClass objects and encoding to stdClass objects are always symmetrical.
So if you plan to do cyclical conversion between the PHP array and a JSON string, first convert the PHP array to an object. The convert the JSON.