Convert a PHP array to JSON
To convert a PHP array to JSON, you can use the json_encode() function. Hereās how itās done:
<?php
$array = [
"foo" => "bar",
"baz" => "qux",
];
$json = json_encode($array);
echo $json;
This code piece, when run, will produce the following output: {“foo”:”bar”,”baz”:”qux”}. Your PHP array is now a JSON string in an instant!
Letās unwrap the mystique aroundĀ json_encode()
:
- The function json_encode() transforms a PHP value into a JSON value. Arrays, objects, and even basic data types like strings, booleans, and integers can all be used in this way.
- JavaScript Object Notation is what JSON stands for, but don’t let the name fool youāit has applications outside of JavaScript. It’s a simple data-interchange format that’s simple for computers to understand and produce as well as for people to read and write.
When to convert a PHP array to JSON
- Data exchange: You may need to convert PHP arrays to JSON when exchanging data between a server and a web application (before JSON was invented, it wasĀ XML).
- Storing data: Since JSON is a lightweight and readable format, itās commonly used to store complex data structures.
- Work with modern APIs: Most modern APIs such as those for social media platforms and cloud services communicate using JSON, so converting your PHP array to JSON can be necessary to work with these APIs.
Catching array to JSON conversion errors
PHP also provides a function to inspect the last occurred error during JSON encoding/decoding.
$array = [
"foo" => "bar",
"baz" => "qux",
];
$json = json_encode($array);
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_last_error_msg();
}
If something unexpected happens during the JSON encoding, you can get the last error message using json_last_error_msg()
.
But this is an old-fashioned way of doing it if you ask me. You could also simply ask PHP to throw an exception when something goes wrong using theĀ JSON_THROW_ON_ERROR
Ā constant:
try {
$array = [
"foo" => "bar",
"baz" => "qux",
];
$json = json_encode($array, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
exit($exception->getMessage());
}