Search the blog

A great thing about JSON is, among other things, it is very easy to edit by hand should you need to. The default options for json_encode() don’t produce very readable results though.

I recommend adding the the following flags: JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT when you call this function.

Although JSON only supports UTF-8 the default options encode special characters so it can be stored in non-UTF-8-encoded files; JSON_UNESCAPED_UNICODE prevents this. Forward slashes are also escaped by default in case you wish to use the JSON within script tags (this is rare in my opinion); JSON_UNESCAPED_SLASHES prevents this. Finally, JSON_PRETTY_PRINT makes the JSON multiline and indented. Yes, it uses a few extra characters but should you ever need to edit the JSON PHP has generated you will be glad you used this flag.

Here is an example:


$array['foo'] = 'I paid £100 for the computer/laptop';

echo json_encode($array) . PHP_EOL . PHP_EOL; // Default
echo json_encode($array, JSON_UNESCAPED_UNICODE) . PHP_EOL . PHP_EOL; // Notice the £ sign is shown as is
echo json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL . PHP_EOL; // Forward slashes are no longer escaped
echo json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); // Now it's multiline and indented properly


{"foo":"I paid \u00a3100 for the computer\/laptop"}

{"foo":"I paid £100 for the computer\/laptop"}

{"foo":"I paid £100 for the computer/laptop"}

    "foo": "I paid £100 for the computer/laptop"


Note that I have avoided using JSON_NUMERIC_CHECK because this can cause unexpected results if you have leading zeros on a number.

Tim Bennett is a Leeds-based web designer from Yorkshire. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.