JSON in PHP

JSON is the text form that one program sends to another. PHP turns its arrays into that text with json_encode and reads it back with json_decode.

json_encode

Function json_encode turns an array into a JSON string. Keys become JSON names and values keep their types.

Use it whenever PHP must send structured data to another system.

<?php $data = ["name" => "Ada", "score" => 42]; echo json_encode($data), PHP_EOL;

php encode.php

{"name":"Ada","score":42}

The array keys became the quoted names of the object, and the number stayed a number: quotes appear only around the text.

json_decode to array

Function json_decode turns a JSON string back into PHP data. Pass true as second argument to get an array instead of an object.

Read the reference json_decode for nested examples.

<?php $json = "{\"name\":\"Ada\",\"score\":42}"; $result = json_decode($json, true); $object = json_decode($json); echo $result["name"], PHP_EOL; echo $object->name, PHP_EOL; var_dump(is_array($result));

php decode.php

Ada
Ada
bool(true)

The same text answers both forms: the array is read with square brackets and the object with an arrow, and the dump proves that the second argument gave an array.

json_last_error

Invalid JSON returns null, so always check the error state.

Function json_last_error returns a code and json_last_error_msg explains it. Validate input early to keep failures easy to locate.

<?php $bad = "{broken}"; $value = json_decode($bad); var_dump($value); echo json_last_error(), PHP_EOL; echo json_last_error_msg(), PHP_EOL;

php errors.php

NULL
4
Syntax error

The decode gave null without a word, and only the two functions after it say why: the code 4 is the syntax error, and the message names it.

Build a tiny JSON response

Set the JSON content header before any output. Encode a small array with status and data keys.

The browser or client receives one clean JSON document.

<?php header("Content-Type: application/json"); $data = ["status" => "ok", "count" => 2]; echo json_encode($data);

The header call only means something in a web request: the server sends the line and the client reads the body as JSON. On the command line the header is ignored and only the body of the document is printed.

Exercises

  1. Encode a list of three names and run it. What do the outer square brackets of the output tell a client?
  2. Decode the output of encode.php without the second argument and read the name with an arrow. Why does the square bracket form fail?
  3. Pass "[1,2,3]" to json_decode and print the second element.
  4. Break the JSON of decode.php on purpose, then print json_last_error_msg(). Which message do you get?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does json_encode() turn an array into?

    Answer

    A JSON string

    The function returns text in JSON form, ready to send or store.

  2. What does the second argument true of json_decode() give?

    Answer

    An array instead of an object

    With true the decoder builds arrays, so keys are read with square brackets; without it you get objects.

  3. What does json_decode() return for invalid JSON?

    Answer

    null, with the reason in json_last_error()

    The decode fails quietly with null; the error code and message describe the failure.

  4. Which header tells a client that a response is JSON?

    Answer

    Content-Type: application/json

    The content type names the format of the body; Accept is a request header, not a response one.

  5. What does this program print? <?php echo json_encode(["a" => 1, "b" => 2]);

    Answer

    {"a":1,"b":2}

    The string keys become JSON names and the values stay numbers, so the object is printed with braces.

  6. What does this program print? <?php echo json_encode(["x", "y"]);

    Answer

    ["x","y"]

    A list with the keys 0 and 1 becomes a JSON array, written with square brackets.

  7. What does this program print? <?php echo json_decode('{"a":1}', true)["a"];

    Answer

    1

    The decode gives an array whose key a holds the integer 1, which echo prints.

  8. What does this program print? <?php $value = json_decode("{broken}"); var_dump($value);

    Answer

    NULL

    Invalid JSON decodes to null, and var_dump shows the type and the value NULL.

  9. What does this program print? <?php json_decode("{broken}"); echo json_last_error_msg();

    Answer

    Syntax error

    The message function turns the error code into text, and this error is a syntax error.

  10. What does json_last_error() give after a successful decode?

    Answer

    JSON_ERROR_NONE, the code 0

    A successful decode resets the error state to the code 0, which the constant JSON_ERROR_NONE names.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev