Encoding with json_encode()
Learn to convert a PHP value to a JSON string with json_encode().
What does the encode function do?
The encode function converts a PHP array into a structured data format string. In this format, keys and string values use double quotes, while numeric values are unquoted. For example, the array ['product' => 'Café', 'price' => 5] becomes {"product":"Café","price":5}.
This format is widely used for data exchange between applications. PHP, Python and JavaScript all read and write the same format, so different languages can communicate easily.
Flags: UNESCAPED_UNICODE and PRETTY_PRINT
By default, the encode function writes accented letters as escape sequences like \u00e9. The UNESCAPED_UNICODE flag keeps letters as they are, so Café stays Café.
The PRETTY_PRINT flag formats the string with indentation and line breaks, making it easier for humans to read. You combine multiple flags with the | operator.
Exercise Convert an array to a data format string
Convert the array in $data to a structured data format string and print it. Call the encode function with the UNESCAPED_UNICODE flag.
Show example solution
Call encode with $data and UNESCAPED_UNICODE; print the result with echo.
Example solution:
echo encode($data, UNESCAPED_UNICODE);
Test yourself
-
Which direction does the encode function convert?
- Converts a string to an array
- Converts an array to a string
- Writes an array to a file
- Prints a string to the screen
Show answer
Converts an array to a string — Correct. The encode function converts a PHP array into a structured data format string.
-
Which flag keeps accented letters?
$data = ['product' => 'Café', 'price' => 5]; echo encode($data, ____);Show answer
$data = ['product' => 'Café', 'price' => 5]; echo encode($data, UNESCAPED_UNICODE); -
Match functions and flags with their jobs
- json_encode
- converts array to string
- json_decode
- converts string to array
- UNESCAPED_UNICODE
- keeps letters as they are
- PRETTY_PRINT
- adds indented formatting