PHP › JSON Handling in PHP

How do you convert a PHP array or object into a JSON formatted string using json_encode?

Beginner

Answer

The json_encode function converts a PHP array or object into a JSON formatted string, which is the standard, widely used data format for exchanging information between different systems, such as sending a response from a PHP API to a JavaScript based frontend, and it automatically handles converting PHP's native data types, like arrays, strings, and booleans, into their correct corresponding JSON representations.
$data = ['name' => 'Ali', 'age' => 30];
echo json_encode($data);
Real-world example An API endpoint uses json_encode to convert an array of product data retrieved from the database into a JSON response, which the frontend JavaScript application then parses to display the products on the page.

Common follow-ups: How do you make json_encode produce nicely formatted, indented output?;What happens if the array you are encoding contains a resource type that cannot be represented in JSON?