To return a JSON response from a PHP server, you can use the json_encode()
function to convert an array or object to a JSON string, and then use the echo
statement to output the JSON string to the client.
Here is an example of how to return a JSON response from a PHP server:
<?php
$data = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
// Convert the data to a JSON string
$json = json_encode($data);
// Set the content type to JSON
header('Content-Type: application/json');
// Output the JSON string
echo $json;
In this example, the $data
array is converted to a JSON string using the json_encode()
function, and then the Content-Type
header is set to application/json
to indicate that the response is a JSON object. Finally, the JSON string is outputted to the client using the echo
statement.
You can also use the header()
function to specify other HTTP headers, such as the Access-Control-Allow-Origin
header to allow cross-origin requests.
Here is an example of how to return a JSON response with the Access-Control-Allow-Origin
header set to *
:
<?php
$data = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
// Convert the data to a JSON string
$json = json_encode($data);
// Set the content type to JSON and allow cross-origin requests
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
// Output the JSON string
echo $json;
Note that the header()
function must be called before any output is sent to the browser, so it should be the first thing you do in your script.