How to Send a JSON-Formatted Response from PHP

In PHP, the json_encode() function is used to convert a PHP variable to a JSON-formatted string. This function takes one parameter, the variable that you want to convert, and returns the JSON-formatted string.

To send a JSON-formatted response to the browser, you need to set the HTTP header of the response to “Content-Type: application/json” using the header() function. This tells the browser that the content being sent back is in JSON format.

Here’s an example of how you can use the json_encode() and header() functions to send a JSON-formatted response to the browser:

<?php
header('Content-Type: application/json');
$data = array("name" => "Ashish", "age" => 30);
echo json_encode($data);

In this example, we first set the HTTP header of the response to “Content-Type: application/json” using the header() function. Next, we create an array called $data that contains some data. Finally, we use the json_encode() function to convert the $data array into a JSON-formatted string and then echo (print) that string to the browser.

It’s important to note that the header() function must be called before any other output is sent to the browser. This is because headers are sent as part of the HTTP response and must be sent before the actual content of the response.

In this way you can send json data to browser. JSON is widely used for data interchange between different systems, it is lightweight and can be easily parsed and generated by different languages.