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();
}
?>
$.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.
<?php
$siteData = [
'name' => 'Codingwithsonu',
'author' => 'Sonu Kumar Pandit',
'topics' => ['PHP', 'MySQL', 'HTML', 'jQuery'],
'published' => true,
];
?>
{
"name": "Codingwithsonu",
"author": "Sonu Kumar Pandit",
"topics": [
"PHP",
"MySQL",
"HTML",
"jQuery"
],
"published": true
}
json_decode($json, true)['name'] = Codingwithsonujson_decode($json, true)['topics'][1] = MySQLjson_decode($json)->published (as object) =
true
This is real output from feeding a string with a trailing comma - [..., "MySQL",] - into json_decode():
json_last_error(): 4json_last_error_msg(): Syntax error
5) Best Practices & Common Mistakes
| Issue | Problem | Fix |
|---|---|---|
Not checking json_last_error() | Silent bad data treated as valid | Always check after json_decode() |
Forgetting the true flag | Get a stdClass when an array was expected | Pass true for associative arrays |
| Encoding a resource or recursive structure | json_encode() returns false | Check the return value before using it |
| Not setting the response header | Clients may not parse it as JSON | Send header('Content-Type: application/json') on API endpoints |