How to convert an array to JSON
Short answer
json_encode() turns an array into a JSON string:
<?php
echo json_encode(['name' => 'Anna', 'age' => 25]);Output:
{"name":"Anna","age":25}Non-ASCII letters and a readable layout
The flags are joined with a vertical bar:
<?php
echo json_encode(['city' => 'Zürich'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);Output:
{
"city": "Zürich"
}A list or an object
An array with keys numbered from zero becomes a list, any other becomes an object:
<?php
echo json_encode(['a', 'b']), ' ', json_encode([1 => 'a', 2 => 'b']);Output:
["a","b"] {"1":"a","2":"b"}Functions used in this recipe
- json_encode — Converts a value to a JSON string.
- json_decode — Parses a JSON string.