JSON in PHP
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.
$data = ["name" => "Ada", "score" => 42];
echo json_encode($data);
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.
$json = "{\"name\":\"Ada\",\"score\":42}";
$result = json_decode($json, true);
echo $result["name"];
var_dump($result);
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.
$bad = "{broken}";
json_decode($bad);
echo json_last_error();
echo json_last_error_msg();
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.
header("Content-Type: application/json");
$data = ["status" => "ok", "count" => 2];
echo json_encode($data);
Next: Reading and writing files
Article author: Arthur Isaev