[PHP] Encode an array or object as a JSON string

Created on November 28, 2026

You can use PHP's json_encode function to convert an array or object into a JSON string.

<?php

$data = [
    'name' => 'Tom',
    'age' => 20,
];

echo json_encode($data);

The script produces the following output.

{"name":"Tom","age":20}

To pretty-print JSON for readability, you can pass JSON_PRETTY_PRINT as the second argument to json_encode. To parse a JSON string back into a PHP array or object, you can use json_decode as described in Decode JSON with PHP (in Japanese).

References

PHP