
Convert a PHP array to JSON
Table of contents
The quickest way to convert a PHP array to JSON
You want to convert a PHP array to JSON?
Use json_encode()
. Here’s what works:
$array = [ "foo" => "bar", "baz" => "qux", ]; $json = json_encode($array, JSON_THROW_ON_ERROR); echo $json; // {"foo":"bar","baz":"qux"}
That’s it. You’ve turned your PHP array into a JSON string.
Why convert a PHP array to JSON?
- APIs: Practically all modern APIs expect JSON.
- Data exchange: Passing data between PHP and JavaScript, or from backend to frontend? JSON is your bridge.
- Storage: Need a human-readable, lightweight format for structured data? Use JSON.
- Legacy: Forget XML. JSON won. Stop living in the past.
Catching PHP array to JSON conversion errors
Just calling json_encode($array)
is amateur hour. Handle errors properly:
try { $json = json_encode($array, JSON_THROW_ON_ERROR); } catch (JsonException $e) { exit('JSON encoding error: ' . $e->getMessage()); }
Why do this?
- With
JSON_THROW_ON_ERROR
, PHP throws an exception if something goes wrong. - Debugging silent failures is for people who like pain. Use exceptions.
Pretty-print your JSON
Readable output matters, especially for debugging. Add the JSON_PRETTY_PRINT
flag:
$json = json_encode($array, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
Common issues with json_encode
- Invalid UTF-8: Non-UTF-8 strings will make
json_encode
choke. - Unsupported types: You can’t encode resources, closures, or objects that don’t implement
JsonSerializable
. - Silent failures: If you don’t use
JSON_THROW_ON_ERROR
, you must check manually:
$json = json_encode($array); if (json_last_error() !== JSON_ERROR_NONE) { echo json_last_error_msg(); }
But you shouldn’t be writing legacy code. Just use the error flag and catch exceptions.
Conclusion
- Use
json_encode($array, JSON_THROW_ON_ERROR)
. Don’t skip the error flag. - Handle
JsonException
to avoid headaches. - For readable output, use
JSON_PRETTY_PRINT
. - Don’t pass garbage (resources, closures) to
json_encode
.
Further reading
Did you like this article? Then, keep learning:
- Find out the best PHP packages to enhance your projects in 2025
- Explore Laravel's HTTP client for efficient error handling and exceptions
- Ensure data integrity in Laravel by mastering array validation techniques
- Discover Laravel collections tips to write more powerful array-handling code
- Discover how to filter values in PHP arrays simply and efficiently
- Learn how to convert arrays to JSON for API communication and storage
- Explore PHP functions to manipulate and sort arrays effectively
- Learn how to handle exceptions during JSON encoding in PHP
- Learn effective ways to print and debug PHP arrays, including Laravel helpers