PHP JSON

JSON (JavaScript Object Notation) is a lightweight, text-based data format. It is the standard way web APIs exchange data, and it's exactly what powers the AJAX examples elsewhere on this site (see the jQuery AJAX tutorial). PHP converts between its own arrays/objects and JSON using two functions: json_encode() and json_decode().

1) json_encode() - PHP to JSON

json_encode() turns a PHP array or object into a JSON string. Pass the JSON_PRETTY_PRINT flag to get readable, indented output (handy for debugging or documentation; APIs usually skip it to save bytes).

<?php
  $data = [
    'name'   => 'Sonu',
    'skills' => ['PHP', 'MySQL'],
  ];

  echo json_encode($data, JSON_PRETTY_PRINT);
?>

2) json_decode() - JSON to PHP

json_decode() parses a JSON string back into PHP. By default it returns a stdClass object. Pass true as the second argument to get an associative array instead - usually the more convenient shape to work with.

<?php
  $json = '{"name":"Sonu","skills":["PHP","MySQL"]}';

  $asObject = json_decode($json);
  echo $asObject->name; // Sonu

  $asArray = json_decode($json, true);
  echo $asArray['name']; // Sonu
?>

3) Handling Malformed JSON

json_decode() returns null both for genuinely malformed JSON and for the literal JSON value null, so check json_last_error() (or the friendlier json_last_error_msg()) to tell the difference.

<?php
  $data = json_decode($json, true);

  if (json_last_error() !== JSON_ERROR_NONE) {
    echo "Invalid JSON: " . json_last_error_msg();
  }
?>
JSON is the language of REST APIs and AJAX. When jQuery's $.ajax() or $.getJSON() calls a PHP endpoint, the PHP side almost always finishes with echo json_encode($response);, and the JavaScript side receives it already parsed into an object.

4) Live Demo: Real Encode/Decode Round-Trip

Everything below is executed live by PHP when this page loads - not a static example. A real associative array is defined at the top of this file, encoded to JSON, then decoded straight back to prove the round-trip works.

4.1 The source PHP array
<?php
  $siteData = [
    'name'      => 'Codingwithsonu',
    'author'    => 'Sonu Kumar Pandit',
    'topics'    => ['PHP', 'MySQL', 'HTML', 'jQuery'],
    'published' => true,
  ];
?>
4.2 json_encode($siteData, JSON_PRETTY_PRINT) output
{
    "name": "Codingwithsonu",
    "author": "Sonu Kumar Pandit",
    "topics": [
        "PHP",
        "MySQL",
        "HTML",
        "jQuery"
    ],
    "published": true
}
4.3 Decoded back into PHP and read
json_decode($json, true)['name'] = Codingwithsonu
json_decode($json, true)['topics'][1] = MySQL
json_decode($json)->published (as object) = true
4.4 What happens with broken JSON

This is real output from feeding a string with a trailing comma - [..., "MySQL",] - into json_decode():

Result: null
json_last_error(): 4
json_last_error_msg(): Syntax error

5) Best Practices & Common Mistakes

IssueProblemFix
Not checking json_last_error()Silent bad data treated as validAlways check after json_decode()
Forgetting the true flagGet a stdClass when an array was expectedPass true for associative arrays
Encoding a resource or recursive structurejson_encode() returns falseCheck the return value before using it
Not setting the response headerClients may not parse it as JSONSend header('Content-Type: application/json') on API endpoints
Next: Continue with Regular Expressions - pattern matching for validating and extracting text, with a live regex tester.