json_encode()
json_encode() converts PHP arrays and objects to a JSON string. Control output with flag constants like JSON_PRETTY_PRINT and JSON_UNESCAPED_UNICODE.
json_encode() converts PHP arrays and objects to a JSON string. Control output with flag constants like JSON_PRETTY_PRINT and JSON_UNESCAPED_UNICODE.
<?php
$data = [
"user" => "Alice",
"age" => 30,
"tags" => ["admin", "editor"],
"meta" => ["joined" => "2024-01-01"],
];
// Compact output
$json = json_encode($data);
// Pretty-printed with Unicode characters preserved
$pretty = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
// Check for errors
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException("JSON encoding failed: " . json_last_error_msg());
}
Use JSON_UNESCAPED_UNICODE to avoid converting non-ASCII characters to \uXXXX escape sequences in your output.