Convert a PHP array to JSON

Convert a PHP array to JSON

Modified
Jul 4, 2025
Written by
Benjamin Crozat
0
comments
2 minutes
read

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: