The json_encode() function in PHP converts a PHP array or object into a JSON formatted string. It is commonly used to send structured data from PHP to JavaScript or APIs.
// General syntax of json_encode
json_encode(value, options, depth)
// Encode a simple associative array
<?php
$data = array("name" => "John", "age" => 30, "city" => "New York");
$json = json_encode($data);
echo $json;
?>
// Encode multiple user records
<?php
$users = array(
array("id" => 1, "name" => "Alice"),
array("id" => 2, "name" => "Bob"),
array("id" => 3, "name" => "Charlie")
);
echo json_encode($users);
?>
// Generate readable formatted JSON
<?php
$data = array(
"name" => "David",
"skills" => array("PHP", "MySQL", "JavaScript")
);
echo json_encode($data, JSON_PRETTY_PRINT);
?>
The output will be a JSON string that can be consumed directly by JavaScript or APIs.
Send JSON data from PHP using echo json_encode() and read it in JavaScript using fetch().
JSON_PRETTY_PRINT for debuggingContent-Type: application/json headerJSON_UNESCAPED_SLASHES